Java OCA OCP Practice Question 2436

Question

Which options can be inserted at //INSERT CODE HERE so the code compiles successfully? (Choose all that apply.)

class Exception1 extends Exception {}
class Exception2 extends Exception {}

class Fish {/* ww  w  .  j  a  va  2 s .c o m*/
    public void swim() throws Exception1 {}
    public void dive() throws Exception2 {}
}

public class Main{
    public static void main(String args[])throws
                                 Exception1, Exception2 {
        try {
            Fish paul = new Fish();
            paul.swim();
            paul.dive();
        }
        //INSERT CODE HERE
    }
}
a  catch(Exception2 | Exception1 e){
       throw e;//from w  ww  . ja  v a2s . com
   }

b  catch(Exception e){
       throw e;
   }

c  catch(Exception2 | Exception1 e){
       throw new Exception2();
   }

d  catch(Exception e){
       throw new Exception();
   }

e  catch(Exception e){
       throw new RuntimeException();
   }


a, b, c, e

Note

Method swim() throws a Exception1, and method dive() throws a Exception2, both checked exceptions.

Method main() is declared to throw both a Exception1 or Exception2.

The code that is inserted at //INSERT CODE HERE must do the following:.

  • The option must use the correct syntax of try with single-catch or multi-catch.
  • Because method main() throws both a Exception1 and Exception2, the try statement might not handle it.
  • It must not throw a checked exception more generic than the ones declared by method main() itself-that is, Exception1 and Exception2.

Option (a) is correct.

It defines the correct syntax to use try with multi-catch, and rethrows the caught instance of Exception1 or Exception2.

Option (b) is correct.

Though the type of the exception caught in the exception handler is Exception, the superclass of the exceptions thrown by main(), the compiler knows that the try block can throw only two checked exceptions, BreathingException or Exception2.

So this thrown exception is caught and rethrown with more inclusive type checking.

Option (c) is correct.

The multi-catch statement is correct syntactically.

Also, the throw statement throws a checked Exception2, which is declared by method main()'s throws clause.

Option (d) is incorrect.

The catch block throws an instance of checked exception Exception, the superclass of the exceptions declared to be thrown by main(), which isn't acceptable.

Option (e) is correct.

It isn't obligatory to include the names of the runtime exceptions thrown by a method in its throws clause.




PreviousNext

Related