Order of catching exceptions in Java

The order is whatever matches first, gets executed (as the JLS clearly explains).

If the first catch matches the exception, it executes, if it doesn’t, the next one is tried and on and on until one is matched or none are.

So, when catching exceptions you want to always catch the most specific first and then the most generic (as RuntimeException or Exception). For instance, imagine you would like to catch the StringIndexOutOfBoundsException thrown by the String.charAt(index) method but your code could also throw a NullPointerException, here’s how you could go to catch the exceptions:

String s = null;
try {
  s.charAt(10);
} catch ( NullPointerExeption e ) {
  System.out.println("null");
  e.printStackTrace();
} catch ( StringIndexOutOfBoundsException e ) {
  System.out.println("String index error!");
  e.printStackTrace();
} catch ( RuntimeException e ) {
  System.out.println("runtime exception!");
  e.printStackTrace();
}

So, with this order, I am making sure the exceptions are caught correctly and they are not tripping over one another, if it’s a NullPointerException it enters the first catch, if a StringIndexOutOfBoundsException it enters the second and finally if it is something else that is a RuntimeException (or inherits from it, like a IllegalArgumentException) it enters the third catch.

Your case is correct as IOException inherits from Exception and RuntimeException also inherits from Exception, so they will not trip over one another.

It’s also a compilation error to catch a generic exception first and then one of it’s descendants later, as in:

try {
  // some code here
} catch ( Exception e) {
  e.printStackTrace();
} catch ( RuntimeException e ) { // this line will cause a compilation error because it would never be executed since the first catch would pick the exception
  e.printStackTrace();
}

So, you should have the children first and then the parent exceptions.

Leave a Comment