Java OCA OCP Practice Question 1747

Question

What is the output of the following application?

package mypkg;/*from w ww.ja v a  2s . com*/


class Exception1 extends Exception {}
public class Main {
  public void m() throw Exception1 {
     throw new ArrayStoreException();
  }
  public static void main(String[] bouncy) {
     try {
        new Main().m();
     } catch (Throwable e) {
        System.out.print("Caught!");
     }
  }
}
  • A. Caught!
  • B. The code does not compile because Exception1 is not handled or declared in the main() method.
  • C. The code does not compile because ArrayStoreException is not handled or declared in the m() method.
  • D. The code does not compile for a different reason.


D.

Note

The code does not compile because the throw keyword is incorrectly used in the m() method declaration.

The keyword throws should have been used instead.

Option D is the correct answer.

Since Exception1 inherits Throwable and the main() method handles Throwable, Exception1 is handled by the main() method, making Option B incorrect.

Option C is also incorrect because ArrayStoreException is an unchecked exception that extends RuntimeException and is not required to be handled or declared.

If throws was used instead of throw, the entire application would compile without issue and print Caught!, making Option A the correct answer.




PreviousNext

Related