Pages

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:

  1. 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.

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

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

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

    ReplyDelete
  5. 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.

    ReplyDelete