scala - Scala 中 NonFatal 和 Exception 的区别

标签 scala exception

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中NonFatalException有什么区别? 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/

相关文章:

scala - 创建 Anyval Option 的又一次尝试

scala - 在 Windows 7 上运行 spark-submit 后无法删除临时文件

c# - 忽略特定类型的异常

powershell - 是否可以在 Powershell 中处理 Get-AzureManagedCache 异常?

python - 在Tkinter中设置错误处理循环

java - 如何编写异常(类x抛出y)

scala - 使用 asInstanceOf 将 Any 转换为 Double?

scala - 分组后将Spark DataFrame的行聚合为String

scala - 如何使用 Intellij Idea 使用 Apache Spark?

java - 删除列表中的所有非唯一成员