The try, catch, and finally blocks
When an exception is thrown inside a try
block, it redirects the control flow to the first catch
clause. If there is no catch
block that can capture the exception (but the finally
block has to be in place), the exception propagates up and out of the method. If there is more than one catch
clause, the compiler forces you to arrange them so that the child exception is listed before the parent exception. Let’s look at the following example:
void someMethod(String s){
try {
method(s);
} catch (NullPointerException ex){
//do something
} catch (Exception ex){
//do something else
}
}
In the preceding example, a catch
block with NullPointerException
is placed before the block with Exception
because NullPointerException...