return is allowed inside the catch block.
What the following code will print out?
public class TestClass{ public static void main(String args[]){ try{ m1(); } catch(IndexOutOfBoundsException e){ System.out.println("1"); throw new NullPointerException(); } catch(NullPointerException e){ System.out.println("2"); return; } catch (Exception e) { System.out.println("3"); } finally{ System.out.println("4"); } System.out.println("END"); } // IndexOutOfBoundsException is a subclass of RuntimeException. static void m1(){ System.out.println("m1 Starts"); throw new IndexOutOfBoundsException( "Big Bang " ); } }(1) exception can only be caught inside the try block. so NullPointerException won't be caught in this case.
(2) return is not reached.
(3) finally will definitely implemented.
(4) "END" won't be reached, for NullPointerException has been thrown to the main method.
print out:
m1 Starts 1 4
Remained question:
if 'return' can stop 'finally' implemented? I remember 'return' is an exception for 'finally'.
no, 'return' cannot stop 'finally' block.
Only if, in a try or catch block, System.exit() is called then finally will not be
executed.
No comments:
Post a Comment