File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in order of exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in order of exception" Watch "Doubt in order of exception" New topic

Doubt in order of exception

Amit Batra
Ranch Hand

Joined: Mar 04, 2006
Posts: 361
This is from the K&B mock

In the above code the order of execution turns out to be
m1catch m2finally except.

My question is if m2() isnt providing a catch yet the main() IS how come when m2() is called, the finally of m2() is shown first and then the catch in main() is displayed? I though if the try block fails, flow control immidiately moves to the catch block and aftre that the finally and the program ends.
Douglas Chorpita
Ranch Hand

Joined: May 09, 2006
Posts: 97
If an exception is not caught, the finally is executed, but all other code is skipped.

Here, in your example, the exception IS being caught. If an exception is caught, code flow returns to normal.

m1() throws an exception, but it catches it. So code flow returns to normal. Then m2() is run. It throws another exception, which is not caught in m2(). The finally-block runs anyway, as the finally block ALWAYS runs. The code jumps ahead to the next catch-block in main() where it is caught. After this, code flow returns to normal. Program exits without an error.

If there would be a method, say m3(), called after the call to m2(), this call would be skipped.

You can have nested try-catch-blocks. When an exception is thrown, the remainder of the try-block is skipped. If the exception is not caught, the finally-block (if there is one) ALWAYS runs. Once this try-catch-block is finished, one might still be in a higher-level try-catch-block. In this case, the remainder of the higher-level try-block is skipped. There is another chance for catch or finally (or both). There can be many levels of try-catch.

[ July 29, 2006: Message edited by: Douglas Chorpita ]

SCJP 1.4 - 95%
Amit Batra
Ranch Hand

Joined: Mar 04, 2006
Posts: 361
Thanks Doug, Thats a solid explanation, its clear now.
I agree. Here's the link:
subject: Doubt in order of exception
It's not a secret anymore!