我想让异常对象在我可以使用的控制台中抛出一个val。类似的东西:
try { ... } catch { e => make e a val }
以便我可以在控制台中执行e.toString
等。
我该怎么做?
答案 0 :(得分:3)
只是不要抓住它。
$ scala
Welcome to Scala version 2.11.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_20).
Type in expressions to have them evaluated.
Type :help for more information.
scala> ???
scala.NotImplementedError: an implementation is missing
at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
... 33 elided
scala> lastException
res1: Throwable = scala.NotImplementedError: an implementation is missing
scala>
另外,更直接:
scala> try { ??? } catch { case e: Throwable => $intp.bind("oops", e) }
oops: Throwable = scala.NotImplementedError: an implementation is missing
res2: scala.tools.nsc.interpreter.IR.Result = Success
scala> oops.toString
res3: String = scala.NotImplementedError: an implementation is missing
答案 1 :(得分:2)
你不能将val移出内部范围,这就是catch块的主体。但是,您可以使用scala.util.Either
表示您可以拥有两个返回值之一:
import scala.util._
val answer = try { Right(...) } catch { case e: Throwable => Left(e) }
answer match {
case Right(r) => // Do something with the successful result r
case Left(e) => // Do something with the exception e
}
答案 2 :(得分:2)
您可以使用Try
,并在其上匹配:
Try(...) match {
case Success(value) => // do something with `value`
case Failure(e) => // `e` is the `Throwable` that caused the operation to fail
}
或者,如果您只是在控制台中乱搞,可以强迫它:
scala> val e = Try(1/0).failed.get
e: Throwable = java.lang.ArithmeticException: / by zero
答案 3 :(得分:2)
别忘了没有什么可以阻止你从catch块返回异常,就像任何其他值一样:
scala> val good = try { 1.hashCode } catch { case e: Throwable => e }
good: Any = 1
scala> val bad = try { null.hashCode } catch { case e: Throwable => e }
bad: Any = java.lang.NullPointerException
但是,除非在try块中返回相同类型的内容,否则会丢失类型信息:
scala> val badOrNull = try { null.hashCode; null } catch { case e: Throwable => e }
badOrNull: Throwable = java.lang.NullPointerException
在这种情况下,如果没有例外情况,您现在会丢失try
的结果。
请参阅其他答案,了解更多类型安全的解决方案,例如Try
或Either
。