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

前端 未结 14 804
一整个雨季
一整个雨季 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条回答
  •  一个人的身影
    2020-11-27 14:32

    A lot of the other answers are looking at things too narrowly.

    As they say, if you are writing application code, you should not catch Throwable. You can't do anything about it, so allowing the surrounding system (JVM or framework) to handle these issues is best.

    However, if you are writing "system code", like a framework or other low-level code then you may very well want to catch Throwable. The reason is to attempt to report the exception, perhaps in a log file. In some cases your logging will fail, but in most cases it will succeed and you will have the information you need to resolve the issue. Once you have made your logging attempt you should then either rethrow, kill the current thread, or exit the entire JVM.

提交回复
热议问题