This is what Wikipedia says about finally clause:
More common is a related clause (finally, or ensure) that is executed whether an exception occurred or not, typically to release resources acquired within the body of the exception-handling block.
Let's dissect your program.
try {
System.out.print(1);
q();
}
So, 1
will be output into the screen, then q()
is called. In q()
, an exception is thrown. The exception is then caught by Exception y
but it does nothing. A finally clause is then executed (it has to), so, 3
will be printed to screen. Because (in method q()
there's an exception thrown in the finally clause, also q()
method passes the exception to the parent stack (by the throws Exception
in the method declaration) new Exception()
will be thrown and caught by catch ( Exception i )
, MyExc2
exception will be thrown (for now add it to the exception stack), but a finally in the main
block will be executed first.
So in,
catch ( Exception i ) {
throw( new MyExc2() );
}
finally {
System.out.print(2);
throw( new MyExc1() );
}
A finally clause is called...(remember, we've just caught Exception i
and thrown MyExc2
) in essence, 2
is printed on screen...and after the 2
is printed on screen, a MyExc1
exception is thrown. MyExc1
is handled by the public static void main(...)
method.
Output:
"132Exception in thread main MyExc1"
Lecturer is correct! :-)
In essence, if you have a finally in a try/catch clause, a finally will be executed (after catching the exception before throwing the caught exception out)