What will be the output when the following code is compiled and run?
//in file Test.java class Exception1 extends Exception{ } class Exception2 extends Exception1 { } class Test{ //from ww w .ja va 2s. co m public static void main (String [] args){ try{ throw new Exception2 (); } catch (Exception1 e){ System .out.println ("Exception1"); } catch (Exception e){ System .out.println ("E"); } finally{ System .out.println ("Finally"); } } }
Select 1 option
Correct Option is : B
Since Exception2 is a sub class of Exception1, catch(Exception1 e) will be able to catch exceptions of class Exception2.
Therefore E 1 is printed.
Once the exception is caught the rest of the catch blocks at the same level are ignored.
So E is not printed. finally is always executed (except in case of System.exit()
), so Finally is also printed.