What will be the output when the following program is run?
package mypkg;//from w ww . j a va2 s .c o m public class Main{ public static void main (String [] args) { try{ hello (); } catch (MyException me){ System.out.println (me); } } static void hello () throws MyException{ int [] dear = new int [7]; dear [0] = 747; foo (); } static void foo () throws MyException{ throw new MyException ("Exception from foo"); } } class MyException extends Exception { public MyException (String msg){ super (msg); } }
Assume that line numbers printed in the messages given below are correct.
Select 1 option
A. Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at mypkg.Main.doTest (Main.java:24)// w w w.j a va 2 s. c o m at mypkg.Main.main (Main.java:14) B. Error in thread "main" java.lang.ArrayIndexOutOfBoundsException C. mypkg.MyException: Exception from foo D. mypkg.MyException: Exception from foo at mypkg.Main.foo (Main.java:29) at mypkg.Main.hello (Main.java:25) at mypkg.Main.main (Main.java:14)
Correct Option is : C
Note that there are a few questions in the exam that test your knowledge about how exception messages are printed.
When you use System.out.println (exception), a stack trace is not printed.
Just the name of the exception class and the message is printed.
When you use exception.printStackTrace()
, a complete chain of the names of the methods called, along with the line numbers, is printed from the point where the exception was thrown and up to the point where the exception was caught and printStackTrace()
was called.