1

在 Python 中,我可以执行以下操作:

try{
 something
}
except{
whoops that didn't work, do this instead 
}

我试图弄清楚是否有办法在 Scala 中做同样的事情。我看到了很多捕获异常的方法,但我还没有看到忽略异常并做其他事情的方法。

编辑:

所以这是我在 Scala 中尝试过的:

try{ 
 something
}
catch{
 case ioe: Exception => something else
}

不过好像不太喜欢。。。

4

2 回答 2

7

我看不出 scala 的 try-catch 不符合您的需求的任何原因:

scala> val foo = 0
foo: Int = 0

scala> val bar = try { 1 / foo } catch { case _: Exception => 1 / (foo + 1) } 
bar: Int = 1
于 2013-06-30T20:05:40.280 回答
2

的一些免费广告scala.util.Try,它有额外的设施,其中最重要的是 scalac 不会因为包罗万象而骚扰你:

scala> try { ??? } catch { case _ => }
<console>:11: warning: This catches all Throwables. If this is really intended, use `case _ : Throwable` to clear this warning.
              try { ??? } catch { case _ => }
                                       ^

scala> import scala.util._
import scala.util._

scala> Try { ??? } map (_ => 1) recover { case _ => 0 } foreach (v => Console println s"Done with $v")
Done with 0
于 2013-06-30T23:54:21.340 回答