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

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

    I'll go a slightly different route from others.

    There are many cases where you would want to catch Throwable (mainly to log/report that something evil happened).

    However, you need to be careful and rethrow anything that you cannot deal with.

    This is especially true of ThreadDeath.

    If you ever catch Throwable, be sure to do the following:

    try {
        ...
    } catch (SomeExceptionYouCanDoSomethingWith e) {
        // handle it
    } catch (ThreadDeath t) {
        throw t;
    } catch (Throwable t) {
        // log & rethrow
    }
    

提交回复
热议问题