在 this article ,据说:
If you want to catch “everything” that would normally happen, then use NonFatal:
import scala.util.control.NonFatal
try {
operation()
} catch {
case NonFatal(e) => errorHandler(e)
}
但我通常使用Exception
:
try {
operation()
} catch {
case e: Exception => errorHandler(e)
}
我想知道Scala中NonFatal
和Exception
有什么区别? Scala 中的Exception
是否包含致命异常?
据我所知,java中,Exception
用于非 fatal error ,Error
用于 fatal error 。 scala 与 java 在异常
方面有什么不同吗?
哪种方法是捕获非致命异常的正确方法?
最佳答案
编辑:更新为最新的 Scala 版本(2.11+ 对 NonFatal.apply
有不同的定义)。
NonFatal
只是一个方便的提取器,定义于 scala.util.control
:
object NonFatal {
/**
* Returns true if the provided `Throwable` is to be considered non-fatal, or false if it is to be considered fatal
*/
def apply(t: Throwable): Boolean = t match {
// VirtualMachineError includes OutOfMemoryError and other fatal errors
case _: VirtualMachineError | _: ThreadDeath | _: InterruptedException | _: LinkageError | _: ControlThrowable => false
case _ => true
}
/**
* Returns Some(t) if NonFatal(t) == true, otherwise None
*/
def unapply(t: Throwable): Option[Throwable] = if (apply(t)) Some(t) else None
}
JVM 上没有特殊的“致命”异常 - Error
并不总是“致命的”,它们只是一种特殊的内部异常。 “致命”异常只是 NonFatal
中使用的异常列表。定义。在这个术语中所有Exception
除了 InterruptedException
被认为是非致命的。考虑InterruptedException
是有道理的。 fatal 因为这意味着线程被中断,所以如果你想处理它,你应该显式地处理。
NonFatal
提取器还处理 ControlThrowable
正确。这些是由特殊控制传输函数(如 break
)引发的异常。里面breakable
.
关于scala - Scala 中 NonFatal 和 Exception 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29744462/