【问题标题】:Cleaner way to throw exception if unable to get return value from Try execution如果无法从 Try 执行中获取返回值,则抛出异常的更简洁方法
【发布时间】:2016-09-25 02:41:47
【问题描述】:

我在使用 Scala 奇妙的 Try 构造时看到的一个常见模因是:

Try(canThrowException) match {
  case Success(result) => result
  case Failure(e) => throw new Exception("Couldn't do it", e)
}

我经常想让这个结构更优雅一点:

Try(canThrowException).getOrElse(throw new Exception("Couldn't do it"))

这样做消除了我链接canThrowException 引发的异常的能力,但看起来更漂亮。

您知道一种同时拥有优雅构造和异常链的方法吗?

【问题讨论】:

  • 可以添加扩展方法;例如def throw(): Success[A]def getOrThrow: Adef throw(f: Throwable => Nothing): Success[A]def getOrThrow(f: Throwable => Nothing): A

标签: scala exception-handling try-catch


【解决方案1】:

试试recover[U >: T](f: PartialFunction[Throwable, U]): Try[U]:

Try(canThrowException) recover {
  case NonFatal(e) => throw new Exception("Couldn't do it", e)
} get

get 部分确实很难看,但鉴于您刚刚处理了所有合理的异常,您只剩下不合理(并重新抛出)的异常。

【讨论】:

    【解决方案2】:

    通常,recoverWith(并留在 Try)可能比实际抛出更好:

    val t = Try(canThrowException)
    
    t recoverWith {
      case (e: Throwable) => { Failure(new Exception("Couldn't do it", e)) }
    }
    

    【讨论】:

    • 您的示例都没有保留异常链接。第一个示例可以简单地链接,因为e 已经在范围内,但我不完全确定如何在第二个示例中链接异常,如果可能的话。
    猜你喜欢
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    相关资源
    最近更新 更多