Scala中的非生育与异常之间的差异 [英] The difference between NonFatal and Exception in Scala

查看:179
本文介绍了Scala中的非生育与异常之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章中,据说:


如果你想抓住通常发生的一切,那么使用
NonFatal:

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)
}

但是我通常使用异常

try {
  operation()
} catch {
  case e: Exception => errorHandler(e)
}

我想知道<$在Scala中的c $ c> NonFatal 和异常? Scala中的异常包括致命异常?

I would like to know what is the difference between NonFatal and Exception in Scala? Does Exception in Scala include fatal exception?

Java中的AFAIK,异常是非致命错误,错误是致命的错误。 scala与java的区别在于异常

AFAIK in java, Exception is for non-fatal error and Error is for fatal error. Is scala different with java in term of Exception?

正确的方法是捕获非致命异常?

Which way is the correct one to catch non-fatal exception?

推荐答案

NonFatal 只是一个方便的提取器, code> scala.util.control :

NonFatal is just a convenient extractor which is defined in 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 {
     case _: StackOverflowError => true // StackOverflowError ok even though it is a VirtualMachineError
     // VirtualMachineError includes OutOfMemoryError and other fatal errors
     case _: VirtualMachineError | _: ThreadDeath | _: InterruptedException | _: LinkageError | _: ControlThrowable | _: NotImplementedError => 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上没有特殊的致命异常 - 错误并不总是致命,它们只是一种特殊的内部异常。 致命异常只是在 NonFatal 定义中使用的异常列表。在这个术语中,除 InterruptedException 之外的所有异常被认为是非致命的。考虑 InterruptedException 是有意义的,因为这意味着线程被中断,所以如果你想处理它,你应该明确地做。

There is no special "fatal" kind of exceptions on JVM - Errors are not always "fatal", they're just a special kind of internal exceptions. "Fatal" exceptions are just a list of exceptions used in NonFatal definition. In this terminology all Exceptions except InterruptedException are considered non-fatal. It makes sense to consider InterruptedException fatal because it means that the thread is interrupted, so if you want to handle it you should do it explicitly.

NonFatal 提取器还正确处理 ControlThrowable 。这些是由 break 中的特殊控制传输函数抛出的异常, breakable

NonFatal extractor also handles ControlThrowables correctly. These are exceptions which are thrown by special control transfer functions like break inside breakable.

这篇关于Scala中的非生育与异常之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆