ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class MyException extends RuntimeException {
    MyException(String m) { super(m); }
}
public class Main {
    public static void main(String[] args) {
        try {
            try {
                throw new MyException("inner");
            } catch (IllegalArgumentException e) {
                System.out.print("wrong-catch ");
            }
        } catch (MyException e) {
            System.out.print("right-catch:" + e.getMessage());
        }
    }
}
  1. A. wrong-catch
  2. B. right-catch:inner
  3. C. wrong-catch right-catch:inner
  4. D. Compilation error: MyException is never caught

Correct answer: B. right-catch:inner

MyException is not an IllegalArgumentException, so the inner catch doesn't match and the exception propagates to the outer try's catch(MyException), which correctly matches, printing "right-catch:inner". The inner catch block is simply skipped entirely, not partially entered.

More OOP with C++ and Java questions

Exams that ask this topic