Java OCA OCP Practice Question 462

Question

What will be the output when the following program is run?

package exceptions; 
public class Main  { 
    public static void main (String [] args)  { 
        try{ //w ww.j  av a2s .  com
            doTest (); 
        } catch (MyException me){ 
            System.out.println (me); 
        } 
     } 
     
    static void doTest () throws MyException{ 
        int [] array = new int [10]; 
        array [10] = 1000; 
        doAnotherTest (); 
     } 
     
    static void doAnotherTest () throws MyException{ 
        throw new MyException ("Exception from doAnotherTest"); 
     } 
} 
class MyException extends Exception  { 
    public MyException (String msg){ 
        super (msg); 
    } 
} 

Select 1 option

A. Exception in thread "main" 
   java.lang.ArrayIndexOutOfBoundsException: 10 
    at exceptions.Main.doTest (Main.java:24) 
    at exceptions.Main.main (Main.java:14) 
    //  w w w  . j  a v a2 s . c  o m
B. Error in thread "main" java.lang.ArrayIndexOutOfBoundsException 

C. exceptions.MyException: Exception from doAnotherTest 

D. exceptions.MyException: Exception from doAnotherTest 

    at exceptions.Main.doAnotherTest (Main.java:29) 
    at exceptions.Main.doTest (Main.java:25) 
    at exceptions.Main.main (Main.java:14) 


Correct Option is  : A

Note

A. is correct.

java.lang.ArrayIndexOutOfBoundsException: 10 
    at exceptions.Main.doTest (Main.java:24) 
    at exceptions.Main.main (Main.java:14) 

You are creating an array of length 10.

Since array numbering starts with 0, the last element would be array [9].

array [10] would be outside the range of the array and therefore an ArrayIndexOutOfBoundsException will be thrown, which cannot be caught by catch (MyException) clause.

The exception is thrown out of the main method and is handled by the JVM's uncaught exception handling mechanism, which prints the stack trace.

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.




PreviousNext

Related