Java OCA OCP Practice Question 420

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{ //  w ww  .j  ava2 s . com
            m2 (); 
         } 
        finally{ 
            m3 (); 
         } 
        catch  (NewException e){} 
     } 

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

    public static void m3 () throws AnotherException{ throw new AnotherException();} 

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.


Correct Option is  : D

Note

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.

Unless it is a try with resources statement.

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

try  {      
   ... 
}  
catch  (SQLException  | IOException  | RuntimeException e)  {      
  e.printStackTrace ();  
} 



PreviousNext

Related