Java OCA OCP Practice Question 673

Question

What will the following program print when run using the command line: java Main

public class Main  { 

   public static void methodX () throws Exception  {  
      throw new AssertionError (); 
    }   // ww  w. j a  va 2 s  .  com

   public static void main (String [] args)  { 
      try{  
         methodX ();  
      }catch (Exception e)  { 
        System.out.println ("EXCEPTION"); 
      } 
    } 
} 

Select 1 option

  • A. It will throw AssertionError out of the main method.
  • B. It will print EXCEPTION.
  • C. It will not compile because of the throws clause in methodX().
  • D. It will end without printing anything because assertions are disabled by default.


Correct Option is  : A

Note

For Option A.

A subclass of Error cannot be caught using a catch block for Exception because java.lang.Error does not extend java.lang.Exception.

For Option B.

The catch block will not be able to catch the Error thrown by methodX().

For Option C.

The throws clause is valid even though unnecessary in this case. D.

It will end without printing anything because assertions are disabled by default.

It is true that assertions are disabled by default however, methodX() is throwing an AssertionError explicitly like any other Throwable.

Here, the assertion mechanism is not even used.




PreviousNext

Related