ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Task {
    void execute() throws Exception {
        try {
            riskyStep();
        } catch (RuntimeException e) {
            throw new Exception("wrapped: " + e.getMessage(), e);
        }
    }
    void riskyStep() { throw new ArithmeticException("div by zero"); }
}
// in main:
try {
    new Task().execute();
} catch (Exception e) {
    System.out.println(e.getMessage() + " / cause: " + e.getCause().getClass().getSimpleName());
}
  1. A. Compilation error: execute() cannot catch RuntimeException and declare throws Exception
  2. B. wrapped: div by zero / cause: ArithmeticException
  3. C. div by zero / cause: Exception
  4. D. wrapped: div by zero / cause: Exception

Correct answer: B. wrapped: div by zero / cause: ArithmeticException

riskyStep() throws an unchecked ArithmeticException, caught by execute()'s catch(RuntimeException e), which wraps it in a checked Exception carrying the original as its cause. main's catch retrieves getMessage() ("wrapped: div by zero") and getCause()'s class (ArithmeticException).

More OOP with C++ and Java questions

Exams that ask this topic