java_doctor_101
java_doctor_101

Reputation: 3357

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?

Upvotes: 0

Views: 123

Answers (3)

Ian S.
Ian S.

Reputation: 1951

If you have multiple exceptions which all are extending from...we'll say IndexOutOfBoundsException, then unless you specifically want to print a different message for StringIndexOutOfBoundsException or another sub-class you should catch an IndexOutOfBoundsException. On the other hand if you have multiple exceptions extending from the Exception class, it is proper format to create a multi-catch statement at least in JDK 1.8:

try {
    // Stuff
}catch(InterruptedException | ClassNotFoundException | IOException ex) {
    ex.printStackTrace();
}

The former one where you create multiple catch statements is if you were trying to do what I said before.

try {
    // Stuff
}catch(StringIndexOutOfBoundsException se) {
    System.err.println("String index out of bounds!");
}catch(ArrayIndexOutOfBoundsException ae) {
    System.err.println("Array index out of bounds!");
}catch(IndexOutOfBoundsException e) {
    System.err.println("Index out of bounds!");
}

Upvotes: 1

c0der
c0der

Reputation: 18792

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();
}

Upvotes: 2

Paras
Paras

Reputation: 238

It is good practice to use Exception sub classes rather than Exception class. If you use Exception then it would be difficult to debug. Here is a link for reference http://howtodoinjava.com/best-practices/java-exception-handling-best-practices/#3

Upvotes: 1

Related Questions