Java OCA OCP Practice Question 323

Question

What will be the result of compiling and running the following program ?

class NewException extends Exception  {} 

class AnotherException extends Exception  {} 

public class Main{ 
    public static void main (String [] args) throws Exception{ 
        try{ //from ww  w . ja  v a 2s  . c  o m
            m2 (); 
         } 
        finally{ 
            m3 (); 
         } 
        catch  (NewException e){} 
     } 

    public static void m2 () throws NewException  { throw new NewException (); 

    public static void m3 () throws AnotherException{ throw new AnotherExcep 

} 

Select 1 option

A. It will compile but will throw AnotherException when run. 
B. It will compile but will throw NewException when run. 
C. It will compile and run without throwing any exceptions. 
D. It will not compile. 
E. None of the above.



D

Note

D. is correct, Because a catch block cannot follow a finally block!

Syntax of try/catch/finally is:

try{ 
} 
catch (Exception1 e)  {...  } 
catch (Exception2 e)  {...  } 
... 
catch (ExceptionN e)  {...  } 
finally  {  ...   } 

With a try, either a catch and or finally or both can occur.

A try MUST be followed by at least one catch or finally.

In Java 7, you can collapse the catch blocks into a single one:

try  {      //from w ww . j av a2 s.c  o m
   ... 
}  
catch  (SQLException  | IOException  | RuntimeException e)  {      
  //The class of the actual exception object will be whatever exception 
  //is thrown at runtime. 
  //But the class of the reference e will be the closest common super 
  // class of all the exceptions in the catch block. 
  //From the code above, it will be java.lang.Exception because that 
  //is the most specific class that is a super class for all the three 
  //exceptions. 
  e.printStackTrace ();  
}



PreviousNext

Related