是否有更优雅的方式来写下面的内容?
try {
... // Some throwing code
return first
}
catch {
case e:ExceptionType => {} // No code to execute. Ignore error.
}
return second
Run Code Online (Sandbox Code Playgroud)
Dan*_*ral 36
scala.util.control.Exception.ignoring(classOf[ExceptionType]) {
... // Some throwing code
}
Run Code Online (Sandbox Code Playgroud)
Rex*_*err 16
@Daniel已经提供了用于执行此操作的规范方法.通过其他方法scala.util.control.Exception
查看 - 它们非常有用且通用!
如果您需要从try块中获取返回值,请使用failing
而不是ignoring
(但请注意结果是an Any
,即not typesafe).
您也可以编写自己的异常捕获程序,这对于繁重的工作来说会有点慢,但其他方面也很好用:
class DefaultOn[E <: Exception] {
def apply[A](default: => A)(f: => A)(implicit m: Manifest[E]) = {
try { f } catch { case x if (m.erasure.isInstance(x)) => default }
}
}
object DefaultOn { def apply[E <: Exception] = new DefaultOn[E] }
scala> DefaultOn[NumberFormatException](0) { "Hi".toInt }
res0: Int = 0
Run Code Online (Sandbox Code Playgroud)
或者如果您喜欢选项:
class TryOption[E <: Exception] {
def apply[A](f: => A)(implicit m: Manifest[E]) = {
try { Some(f) } catch { case x if (m.erasure.isInstance(x)) => None }
}
}
object TryOption { def apply[E <: Exception] = new TryOption[E] }
scala> TryOption[NumberFormatException] { "Hi".toInt }
res1: Option[Int] = None
Run Code Online (Sandbox Code Playgroud)
或者你可以从这个以及库例程中获得灵感,并创建自己的方法来忽略多个不同的异常并保留返回值的类型.
在 Scala 中,不会检查所有异常,因此如果您不想要,您可以跳过处理它们(因此异常将升级到更高级别)。以您想要的方式默默地忽略异常通常是一种不好的做法。但是,您的代码可以缩短为:
try {
... // Some throwing code
} catch {
case e:ExceptionType =>
}
Run Code Online (Sandbox Code Playgroud)