Tuesday, October 11, 2011

Try...Catch...Finally Puzzle

I showed a similar example at my last GreenJUG meeting. In the example code below, I have a try{...}catch(Exception e) {...}finally{...} puzzle.

Before running the code ask yourself three questions: does it compile, does it run, and what is the result?

Tell me what the expected result is supposed to be and why?

Main.java


The example code is a NetBeans project and can be downloaded here: FinallyReturn.zip

5 comments :

Branden said...

It should print out the message - you caught the first exception, so the catch block executes, and the finally block always executes so it'll print the message.

John Yeary said...

Yes, it did print the message. Did you notice anything else?

evanchooly said...

No exception gets thrown because of the return in the finally.

Edouard said...

And the "NullPointerException 2" is never catched...

Andy Bailey said...

The return statement causes the Thread private method exit() to be cause which clears several references including the one for uncaughtExceptionHandler, so no exceptions will be caught after the main method exits.

Popular Posts