简体   繁体   English

斯卡拉(Scala):Throwable的保证是什么?

[英]Scala: what are the guarantees of the catch Throwable?

I would like to know the guarantees of the following pattern: 我想知道以下模式的保证:

try {
  //business logic here
} catch {
  case t: Throwable =>
    //try to signal the error
    //shutdown the app
}

I'm interested in catching all unexpected exceptions (that can be thrown by any framework, library, custom code etc...), trying to record the error and shutting down the virtual machine. 我对捕获所有意外异常(可由任何框架,库,自定义代码等引发的异常),尝试记录错误并关闭虚拟机感兴趣。

In Scala what are the guarantees of the catch Throwable exception? 在Scala中,catch Throwable异常的保证是什么? Are there any differences with the java Exception hierarchy to take in consideration? java Exception层次结构是否有任何差异需要考虑?

Throwable is defined in the JVM spec : ThrowableJVM规范中定义:

An exception in the Java Virtual Machine is represented by an instance of the class Throwable or one of its subclasses. Java虚拟机中的异常由Throwable类或其子类之一的实例表示。

which means that both Scala and Java share the same definition of Throwable. 这意味着Scala和Java都共享Throwable的相同定义。 In fact, scala.Throwable is just an alias for java.lang.Throwable . 实际上, scala.Throwable只是java.lang.Throwable 的别名 So in Scala, a catch clause that handles Throwable will catch all exceptions (and errors) thrown by the enclosed code, just like in Java. 因此,在Scala中,处理Throwable的catch子句将捕获随附代码抛出的所有异常(和错误),就像Java中一样。

There are any difference with the java Exception hierarchy to take in consideration? java Exception层次结构有什么不同要考虑?

Since Scala uses the same Throwable as Java, Exception and Errors represent the same things. 由于Scala使用与Java相同的Throwable,因此Exception和Errors表示相同的内容。 The only "difference" (that I know of) is that in Scala, exceptions are sometimes used under the hood for flow control, so that if you want to catch non-fatal exceptions (thus excluding Errors), you should rather use catch NonFatal(e) instead of catch e : Exception . 唯一的“差异”(据我所知)是在Scala中,有时会在catch NonFatal(e)异常控制以进行流控制,因此,如果要捕获非致命异常(因此不包括错误),则应该使用catch NonFatal(e)代替catch e : Exception But this doesn't apply to catching Throwable directly 但这不适用于直接捕获Throwable

All harmless Throwables can be caught by: 所有无害的可扔物均可被以下物品捕获:

  try {
    // dangerous
  } catch {
    case NonFatal(e) => log.error(e, "Something not that bad.")
  }

This way, you never catch an exception that a reasonable application should not try to catch. 这样,您就永远不会遇到一个合理的应用程序不应尝试捕获的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM