1Z0-811 · Question #56
Given the code fragment: int number = 1; String s = null; try { number = s.length(); number += 2; } catch (RuntimeException e) { number += 4; } System.out.println (number); What is the result?
The correct answer is C. 5. C is correct (5) because s.length() throws a NullPointerException before the assignment to number completes, leaving number still at 1. Since NullPointerException extends RuntimeException, the catch block fires and executes number += 4, giving 1 + 4 = 5. A (1) is wrong because…
Question
Options
- A1
- B3
- C5
- DNothing is printed.
How the community answered
(43 responses)- A14% (6)
- B5% (2)
- C74% (32)
- D7% (3)
Explanation
C is correct (5) because s.length() throws a NullPointerException before the assignment to number completes, leaving number still at 1. Since NullPointerException extends RuntimeException, the catch block fires and executes number += 4, giving 1 + 4 = 5.
- A (1) is wrong because the exception is caught - if it weren't (or if there were no catch block),
numberwould stay at 1, but execution doesn't stop there. - B (3) is wrong because
number += 2is in thetryblock after the line that throws - once the exception is thrown, the rest of thetryblock is skipped entirely. - D is wrong because the exception is handled gracefully; execution reaches
System.out.printlnnormally after the catch block runs.
Memory tip: Think of a try block like a circuit breaker - the moment an exception fires, the current line is abandoned mid-execution and control jumps immediately to the matching catch. Any partial assignment or subsequent lines in the try are skipped.
Topics
Community Discussion
No community discussion yet for this question.