Java OCA OCP Practice Question 604

Question

What is wrong with the following code?

class MyException extends Exception  {} 

public class Main{ 
   public static void main (String [] args){ 
      Main tc = new Main (); 
      try{ //from  ww w  .j a v  a2s .c om
         tc.m1 (); 
       } 
      catch  (MyException e){ 
         tc.m1 (); 
       } 
      finally{ 
         tc.m2 (); 
       } 
    } 
   public void m1 () throws MyException{ 
      throw new MyException (); 
    } 
   public void m2 () throws RuntimeException{ 
      throw new NullPointerException (); 
    } 
} 

Select 1 option

  • A. It will not compile because you cannot throw an exception in finally block.
  • B. It will not compile because you cannot throw an exception in catch block.
  • C. It will not compile because NullPointerException cannot be created this way.
  • D. It will not compile because of unhandled exception.
  • E. It will compile but will throw an exception when run.


Correct Option is  : D

Note

Option A. is wrong.

You have to declare it in the method's throws clause.

Option B. is wrong.

You have to declare it in the method's throws clause.

Option C.

It does have a no args constructor.

The catch block is throwing a checked exception (i.e. non-RuntimeException).

It must be handled by either a try catch block or declared in the throws clause of the enclosing method.

finally is throwing an exception here, but it is a RuntimeException so there is no need to handle it or declare it in the throws clause.




PreviousNext

Related