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());
}- A. Compilation error: execute() cannot catch RuntimeException and declare throws Exception
- B. wrapped: div by zero / cause: ArithmeticException
- C. div by zero / cause: Exception
- 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
- What is printed? cpp class Base { public: virtual void op() { cout << "Base::op "; } void callOp() { this->op(); } }; class Derived…
- What is printed? cpp struct Base { virtual std::string name() const { return "Base"; } }; struct Derived : Base { std::string name() const…
- What is printed? java class Resource { String name; Resource(String n) { name = n; } @Override protected void finalize() {…
- What is printed? cpp class Logger { public: static int instances; Logger() { instances++; } ~Logger() { instances--; } }; int…
- What is printed? cpp struct Event { virtual void handle() const { cout << "generic-event "; } }; struct ClickEvent : Event { void handle()…
- A lambda expression captures a local variable from its enclosing method. What restriction does Java place on that variable?