Why catch Exceptions in Java, when you can catch Throwables?

前端 未结 14 750
一整个雨季
一整个雨季 2020-11-27 13:44

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 an

14条回答
  •  -上瘾入骨i
    2020-11-27 14:13

    Do NOT ever catch Throwable or Error and you should generally not simply catch a generic Exception either. Errors are generally things that most reasonable programs cannot possibly recover from. If you know what is going on, you might be able to recover from one specific error, but in that case, you should catch only that one particular error and not all errors in general.

    A good reason not to catch Error is because of ThreadDeath. ThreadDeath is a fairly normal occurrence that can theoretically be thrown from anywhere (other processes like the JVM itself can generate it), and the whole point of it is to kill your thread. ThreadDeath is explicitly an Error rather than an Exception because too many people catch all Exceptions. If you ever were to catch ThreadDeath, you must rethrow it so that your thread actually dies.

    If you have control over the source, it should probably be restructured to throw an Exception rather than an Error. If you don't, you should probably call to the vendor and complain. Errors should be reserved for only things that are terminal with no possible way to recover from them.

提交回复
热议问题