ProgrammingVery hardWipro · Cognizant pattern

What is printed, and what happens to the RuntimeException?

What is printed, and what happens to the RuntimeException?
static int f() {
    try {
        throw new RuntimeException("x");
    } finally {
        return 5;
    }
}
public static void main(String[] a) { System.out.print(f()); }
  1. A. Prints 5; the RuntimeException is silently discarded, with no warning at compile or run time
  2. B. Throws the RuntimeException at runtime before anything is printed
  3. C. Compilation error: a pending exception cannot be discarded by finally
  4. D. Prints "x5"

Correct answer: A. Prints 5; the RuntimeException is silently discarded, with no warning at compile or run time

A return statement inside finally discards any exception that was propagating out of the try block, just as it discards a pending return value. The method simply returns 5, and the RuntimeException vanishes without any diagnostic.

More OOP with C++ and Java questions

Exams that ask this topic