Java OCA OCP Practice Question 1806

Question

What is wrong with the following code?.

public class Main {
  public static void main(String[] args) throws A {
    try {/* w  w  w .  j a va 2 s. com*/
      f();
    } finally {
      System.out.println("Done.");
    } catch (A e) {
      throw e;
    }
  }

  public static void f() throws B {
    throw new B();
  }
}

class A extends Throwable {}

class B extends A {}

Select the one correct answer.

  • (a) The main() method must declare that it throws B.
  • (b) The finally block must follow the catch block in the main() method.
  • (c) The catch block in the main() method must declare that it catches B rather than A.
  • (d) A single try block cannot be followed by both a finally and a catch block.
  • (e) The declaration of class A is illegal.


(b)

Note

The only thing that is wrong with the code is the ordering of the catch and finally blocks.

If present, the finally block must always appear last in a try-catch-finally construct.




PreviousNext

Related