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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | /* * Copyright 2011 John Yeary <jyeary@bluelotussoftware.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bluelotussoftware.example.se; /** * * @author John Yeary <jyeary@bluelotussoftware.com> * @version 1.0 */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { try { throw new NullPointerException( "NullPointerException 1" ); } catch (NullPointerException e) { throw new NullPointerException( "NullPointerException 2" ); } finally { System.out.println( "Do I ever get printed?" ); return ; } } } |
5 comments :
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.
Yes, it did print the message. Did you notice anything else?
No exception gets thrown because of the return in the finally.
And the "NullPointerException 2" is never catched...
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.
Post a Comment