ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
// static method of the main class:
static int f() {
    try { throw new RuntimeException("t"); }
    finally { return 7; }
}
// in main:
try { System.out.print(f()); }
catch (RuntimeException e) { System.out.print("caught"); }
  1. A. caught
  2. B. 7caught
  3. C. 7
  4. D. Compile-time error: missing return

Correct answer: C. 7

A return in finally completes the method normally and silently discards the pending exception, so f() returns 7 and nothing is caught. (This is why returning from finally is considered bad practice.)

More OOP with C++ and Java questions

Exams that ask this topic