Java OCA OCP Practice Question 265

Question

Given:

class Main {/*from ww  w. j av  a 2 s  .  c o  m*/
  class MyException1 extends Exception { }
  class MyException2 extends Exception { }

  public static void main(String[] args) throws MyException1,
      MyException2 {
    Main a = new Main();
    try {
      a.drive();
      System.out.println("honk!");
    } // insert code here
      System.out.println("error driving");
      throw e;
    }
  }
  void drive() throws MyException1, MyException2 {
    throw new MyException1();
  } 
}

Which inserted independently at // insert code here

will compile and produce the output "error driving" before throwing an exception?

Choose all that apply.

A.  catch(MyException2 e) {
B.  catch(MyException2 | MyException1 e) {
C.  catch(MyException2 e | MyException1 e) {
D.  catch(Exception e) {
E.  catch(IllegalArgumentException e) {
F.  catch(MyException1 e) {
G.  None of the above-code fails to compile for another reason


B, D, and F are correct.

Note

B uses multi-catch to identify both exceptions drive() may throw.

D still compiles since it uses the new enhanced exception typing to recognize that Exception may only refer to MyException2 and MyException1.

F is the simple case that catches a single exception.

Since main throws MyException2, the catch block doesn't need to handle it.

A and E are incorrect because the catch block will not handle MyException1 when drive() throws it.

The main method will still throw the exception, but the println() will not run.

C is incorrect because it is invalid syntax for multi-catch.

The catch parameter e can only appear once.

G is incorrect because of the above.




PreviousNext

Related