为什么捕获Throwables时会捕获Java中的异常? [英] Why catch Exceptions in Java, when you can catch Throwables?

查看:279
本文介绍了为什么捕获Throwables时会捕获Java中的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们最近遇到了Java服务器应用程序的问题,其中应用程序抛出了未捕获的错误,因为Error是Throwable的一个单独子类,我们只捕获异常。

We recently had a problem with a Java server application where the application was throwing Errors which were not caught because Error is a separate subclass of Throwable and we were only catching Exceptions.

我们通过捕获Throwables而不是Exceptions来解决当前的问题,但是这让我想到为什么你想要捕获Exceptions而不是Throwables,因为你会错过错误。

We solved the immediate problem by catching Throwables rather than Exceptions, but this got me thinking as to why you would ever want to catch Exceptions, rather than Throwables, because you would then miss the Errors.

所以,你为什么要捕捉异常,当你能抓住Throwables

推荐答案

这一切都取决于一旦你发现错误你将要做什么。通常,捕获错误可能不应被视为正常异常流程的一部分。如果你确实抓到一个,你不应该考虑继续进行,好像什么也没发生,因为JVM(和各种库)将使用错误作为一种信号发生真正严重的事情并且我们需要尽快关闭。一般来说,最好在他们告诉你结束的时候听他们说。

It all depends a bit on what you're going to do with an Error once you've caught it. In general, catching Errors probably shouldn't be seen as part of your "normal" exception flow. If you do catch one, you shouldn't be thinking about "carrying on as though nothing has happened", because the JVM (and various libraries) will use Errors as a way of signalling that "something really serious has happened and we need to shut down as soon as possible". In general, it's best to listen to them when they're telling you the end is nigh.

另一个问题是,错误的可恢复性可能取决于特定的虚拟机,这是你可以控制或不控制的东西。

Another issue is that the recoverability or not from an Error may depend on the particular virtual machine, which is something you may or not have control over.

这就是说,有一些极端情况下安全和/或需要捕获错误,或至少某些子类:

That said, there are a few corner cases where it is safe and/or desirable to catch Errors, or at least certain subclasses:


  • 在某些情况下,您确实希望停止正常的流程:例如如果你在Servlet中,你可能不希望Servlet运行者的默认异常处理程序向全世界宣告你有一个OutOfMemoryError,无论你是否可以从中恢复。

  • 有时,如果JVM可以从错误原因中干净地恢复,则会抛出错误。例如,如果在尝试分配数组时发生OutOfMemoryError,至少在Hotspot中,您似乎可以安全地从此恢复。 (当然还有其他情况可能会抛出OutOfMemoryError而不能安全地尝试使用它。)

所以底线是:如果你确实捕获了Throwable / Error而不是Exception,它应该是一个明确定义的情况,你知道你正在做一些特别的事情

So the bottom line is: if you do catch Throwable/Error rather than Exception, it should be a well-defined case where you know you're "doing something special".

编辑:可能这很明显,但我忘了说实际上, JVM可能实际上没有在Error上调用你的catch子句。我肯定看到Hotspot明显地掩盖了捕获某些OutOfMemoryErrors和NoClassDefFoundError的尝试。

Possibly this is obvious, but I forgot to say that in practice, the JVM might not actually invoke your catch clause on an Error. I've definitely seen Hotspot glibly gloss over attempts to catch certain OutOfMemoryErrors and NoClassDefFoundError.

这篇关于为什么捕获Throwables时会捕获Java中的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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