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

前端 未结 14 675
一整个雨季
一整个雨季 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:37

    In general it would be reasonable to try to catch Errors if only so that can be properly reported.

    However, I believe there are cases when it would be appropriate to catch an Error and not report it. I'm referring to UnsatisfiedLinkError. In JAI the library uses some native libraries to implement most of the operators for performance reasons, however if the library fails to load (doesnt exist, wrong format, unsupported platform) the library will still function because it will fall back into a java only mode.

    0 讨论(0)
  • 2020-11-27 14:37

    There is no point in catching Error.

    Errors are used to indicate something went really wrong in your application and it should be restarted.

    For instance one common error is

    java.lang.OutOfMemoryError
    

    There is NOTHING you can do when that happens. Is already too late, the JVM has exhausted all its options to get more memory but it is impossible.

    See this other answer to understand more about the three kinds of exceptions.

    0 讨论(0)
提交回复
热议问题