If I’m not mistaken, subclasses of Exceptions should be caught first. But having to catch any RuntimeException and a concrete checked Exception, which should be caught at first?
try {
...
} catch(RuntimeException e) {
...
} catch(IOException e) {
...
}
Is this order a correct one? Or is it correct but a bad option?
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:
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:
So, you should have the children first and then the parent exceptions.