ProgrammingVery hardAmazon/Microsoft SDE MCQ · Java placement
What is printed?
What is printed?
class R implements AutoCloseable {
public void close() { throw new RuntimeException("C"); }
}
// in main:
try {
try { throw new RuntimeException("A"); }
finally { throw new RuntimeException("B"); }
} catch (RuntimeException e) { System.out.print(e.getMessage()); }
try (R r = new R()) {
throw new RuntimeException("A");
} catch (RuntimeException e) {
System.out.print(e.getMessage() + e.getSuppressed().length);
}- A. AA1
- B. BC0
- C. BA1
- D. BA0
Correct answer: C. BA1
An exception thrown from finally replaces the pending one, and A is simply lost: B. In try-with-resources the body's exception A is primary and the exception from close() is attached to it as suppressed, so A1.
More OOP with C++ and Java questions
- Which line fails to compile? java void run() { try { int x = 1; } catch (RuntimeException e) { } // line 1 try { int y = 2; } catch…
- What is printed? java class P { static { System.out.print("1"); } { System.out.print("2"); } P() { System.out.print("3"); } } class C…
- Which line fails to compile? java int base = 10; int step = 1; step = 2; Function<Integer, Integer> f = x -> x + base; // line 1…
- What is printed? java // static methods of the main class: static void f(Object o) { System.out.print("O"); } static void f(int... a) {…
- What is printed? java char c = 'a'; c += 1; System.out.print(('a' + 1) + "" + (char) ('a' + 1) + c);
- What is printed? java Object o = null; String s = (String) o; System.out.print(s + (o instanceof Object) + (s == null));