public class D {
void myMethod() {
try {
throw new IllegalArgumentException();
} catch (NullPointerException npex) {
System.out.println("NullPointerException thrown ");
} catch (Exception ex) {
System.out.println("Exception thrown ");
} finally {
System.out.println("Done with exceptions ");
}
System.out.println("myMethod is done");
}
public static void main(String args[]) {
D d = new D();
d.myMethod();
}
}
I don’t understand how come "myMethod is done" also being printed. Exception was throwed, so it suppose to find a matching catch and do the finally block, but it continues on the myMethod method and prints the myMethod is done, which is not part of the finally block. Why?
This is how try-catch-finally is intended to work. Because you caught the exception, it’s considered to have been dealt with, and execution continues as normal.
If you hadn’t caught it, or had re-thrown it, then “myMethod is done” would not have been printed, and the exception would have bubbled up the stack until it was caught somewhere else.
Note that the
finallyblock always executes, exceptions or no.