Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using Throwable and Exception in a try catch

Sometimes, I see

try {  } catch(Throwable e) {  } 

And sometimes

try {  } catch(Exception e) {  } 

What is the difference?

like image 929
jax Avatar asked Feb 16 '10 15:02

jax


People also ask

What is the difference between throwable and exception?

The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of the Object class. Throwable has two direct subclasses - Exception and Error. The Exception class is used for exception conditions that the application may need to handle.

Why catching throwable instead of hierarchy wise exception classes is a bad idea?

Throwable is a bad idea because in order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable. When you do this, nobody knows what kind of Error this method is going to throw, and until you know what is the problem, how can you resolve that.

What is the use of try-catch throw in exception handling?

The try statement allows you to define a block of code to be tested for errors while it is being executed. The throw keyword throws an exception when a problem is detected, which lets us create a custom error. The catch statement allows you to define a block of code to be executed if an error occurs in the try block.

Does try-catch throw exception?

The try... catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed.


1 Answers

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.

like image 180
Yishai Avatar answered Oct 08 '22 03:10

Yishai