Difference between using Throwable and Exception in a try catch

后端 未结 5 1361
忘了有多久
忘了有多久 2020-11-27 09:03

Sometimes, I see

try {

} catch(Throwable e) {

}

And sometimes

try {

} catch(Exception e) {

}

What is

相关标签:
5条回答
  • 2020-11-27 09:45

    I have seen people use Throwable to catch some errors that might happen due to infra failure/ non availability.

    0 讨论(0)
  • The first one catches all subclasses of Throwable (this includes Exception and Error), the second one catches all subclasses of Exception.

    Error is programmatically unrecoverable in any way and is usually not to be caught, except for logging purposes (which passes it through again). Exception is programmatically recoverable. Its subclass RuntimeException indicates a programming error and is usually not to be caught as well.

    0 讨论(0)
  • 2020-11-27 09:52

    Throwable is super class of Exception as well as Error. In normal cases we should always catch sub-classes of Exception, so that the root cause doesn't get lost.

    Only special cases where you see possibility of things going wrong which is not in control of your Java code, you should catch Error or Throwable.

    I remember catching Throwable to flag that a native library is not loaded.

    0 讨论(0)
  • 2020-11-27 09:55

    By catching Throwable it includes things that subclass Error. You should generally not do that, except perhaps at the very highest "catch all" level of a thread where you want to log or otherwise handle absolutely everything that can go wrong. It would be more typical in a framework type application (for example an application server or a testing framework) where it can be running unknown code and should not be affected by anything that goes wrong with that code, as much as possible.

    0 讨论(0)
  • 2020-11-27 10:02

    Thowable catches really everything even ThreadDeath which gets thrown by default to stop a thread from the now deprecated Thread.stop() method. So by catching Throwable you can be sure that you'll never leave the try block without at least going through your catch block, but you should be prepared to also handle OutOfMemoryError and InternalError or StackOverflowError.

    Catching Throwable is most useful for outer server loops that delegate all sorts of requests to outside code but may itself never terminate to keep the service alive.

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