nerdexam
Oracle

1Z0-808 · Question #30

Given the following code for the classes MyException and Test: ``java public class MyException extends RuntimeException {} public class Test { public static void main(String[] args) { try {…

The correct answer is B. B. Option B is correct because catch (RuntimeException re) in method1() catches both RuntimeException and any of its subclasses - including MyException. Since MyException extends RuntimeException, both branches of the ternary expression produce a RuntimeException (or subtype)…

Handling Exceptions

Question

Given the following code for the classes MyException and Test:
public class MyException extends RuntimeException {}
public class Test {
 public static void main(String[] args) {
 try {
 method1();
 } catch (MyException ne) {
 System.out.print("A");
 }
 }
 public static void method1() { // line n1
 try {
 throw Math.random() > 0.5 ? new MyException() : new RuntimeException();
 } catch (RuntimeException re) {
 System.out.print("B");
 }
 }
}
What is the result?

Options

  • AA
  • BB
  • CEither A or B
  • DA B
  • EA compile time error occurs at line n1

How the community answered

(19 responses)
  • A
    5% (1)
  • B
    58% (11)
  • D
    26% (5)
  • E
    11% (2)

Explanation

Option B is correct because catch (RuntimeException re) in method1() catches both RuntimeException and any of its subclasses - including MyException. Since MyException extends RuntimeException, both branches of the ternary expression produce a RuntimeException (or subtype), which is always caught inside method1(), printing "B" every time. The exception never escapes method1(), so the catch (MyException ne) block in main() is never reached.

  • A is wrong - "A" would require an exception to propagate out of method1() to main(), which never happens since the catch in method1() intercepts everything.
  • C is wrong - it's not random from the caller's perspective; regardless of which exception is thrown, the superclass catch in method1() always handles it.
  • D is wrong - an exception can only be caught once; once caught in method1(), it cannot also propagate to main().
  • E is wrong - the code is perfectly valid; throwing the result of a ternary expression is legal as long as both branches are throwable types.

Memory tip: A catch block for a supertype is a net that catches all subtypes too - "if the parent can catch it, the child is caught first." Always trace where the exception is first caught, not just where it's thrown.

Topics

#exception inheritance#catch block matching#exception propagation#RuntimeException hierarchy

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice