nerdexam
Oracle

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…

Exception Handling and Methods

Question

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?

Options

  • A1
  • B3
  • C5
  • DNothing is printed.

How the community answered

(43 responses)
  • A
    14% (6)
  • B
    5% (2)
  • C
    74% (32)
  • D
    7% (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), number would stay at 1, but execution doesn't stop there.
  • B (3) is wrong because number += 2 is in the try block after the line that throws - once the exception is thrown, the rest of the try block is skipped entirely.
  • D is wrong because the exception is handled gracefully; execution reaches System.out.println normally 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

#NullPointerException#RuntimeException#Try-Catch#Exception Handling

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice