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

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

    Normally when programming, you should only catch a specific exception (such as IOException). In a lot of programs you can see a very toplevel

    try {
        ...
    } catch(Exception e) {
        ...
    }
    

    That catches all errors which could be recoverable and all those which indicate a bug in your code, e.g. InvalidArgumentException, NullPointerException. You can then automatically send an eMail, display a message box or whatever you like, since the JavaVM itself is still working fine.

    Everything derived from Error is something very bad, you can't do anything against. The question is, if it makes sense to catch a OutOfMemoryError or a VirtualMachineError. (It is a error in the JavaVM itself, probably you can't even display a message box or send an eMail then)

    You should probably not a class derived from Error, you should derive from Exception or RuntimeException.

提交回复
热议问题