nitinsh99 nitinsh99 - 2 months ago 13
Java Question

Multiple Catch blocks vs Catching in Base Exception class

Assuming we are talking about all the exceptions that extends base Exception class,

is:

try {
some code;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
catch (MyOwnException e)
{
e.printStackTrace();
}


same as:

try {
some code;
}
catch (Exception e) {
e.printStackTrace();
}


I am wondering in which case I MUST use the former one?

Answer

In the 2nd option Exception will catch all exception, not only those explicitly listed in the first option.
Use the 1st option if you want to catch only selected exceptions, and respond differently to each.
If you want to catch only selected exceptions, and have the same response to all of them, you could use:

catch (InterruptedException | ExecutionException | MyOwnException e)
{
    e.printStackTrace();
}