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()); }- A. Prints 5; the RuntimeException is silently discarded, with no warning at compile or run time
- B. Throws the RuntimeException at runtime before anything is printed
- C. Compilation error: a pending exception cannot be discarded by finally
- 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
- What is printed? java class MyEx extends RuntimeException { public String getMessage() { return "custom:" + super.getMessage(); } } public…
- Does this compile? java interface I { void m() throws java.io.IOException; } class C implements I { public void m() throws…
- What is printed? java class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) {…
- What is printed? java // in main: String a = "hello"; String b = "hello"; String c = new String("hello"); String d = c.intern()…
- What is printed? java // in main: Integer a = 100; Integer b = 100; Integer c = 200; Integer d = 200; System.out.println((a == b) + " " +…
- What is printed? java // in main: String s1 = "Java"; String s2 = new StringBuilder("Java").toString(); System.out.println((s1 == s2) + "…