I am preparing for the SCJP exam using mock exams that come with the SCJP 6 study guide. Since it's Flash I can't copy paste the code, if this doesn't make sense let me know and I will type it over.
One of the questions deals with throwing an runtime exception (RTE)in a class without a catch but with a finally block. So: Try(method code) Finally(finally code)
The finally block simply prints the line "Finally executing".
I understand that the finally block with execute as long as the RTE does not cause the JVM to crash. However, what I don't understand is that the finally block executes first (so it prints the line "Finally Executing") before the JVM Console prints that a RTE has occured.
As the RTE is thrown BEFORE the finally statement can execute. So in my mind I expect the console to print an RTE has occured, then print "Finally Executing". Unless of course Java works in such a way that any exceptions go on the stack and whatever code is listed in the finally block always goes on top of the stack, then the finally block executes first, then the RTE gets printed.
Is that the right way of looking at it?
Woohoo passed SCJP 1.6, that's the theory exam passed now for the practice ;)
Now method2 calls method1. When the exception will occur, finally will be executed and the exception will be propagated to method2. There it will be successfully caught. So there will be no error printed on the console. Now think what will happen if it works your way...
The stack trace consists of only method calls. try-catch-finally are not a part of the stack trace. Just remember that an exception is propagated down the stack trace till a catch block catches it. If no catch block is found, then the thread is suspended. So if the stack trace contains 3 methods
(Remember here main method called method1, method1 called method2) If an exception occurs in method2, the exception will be returned to method1, if method1 also doesn't handle it then it is sent to main and if even main doesn't handle the exception, then the main thread ends (the exception is unhandled so the thread ends)...