nerdexam
Oracle

1Z0-808 · Question #55

Given the code fragment: public static void main(String[] args) { ArrayList myList = new ArrayList(); String[] myArray; try { while (true) { myList.add("My String"); } } Catch (RuntimeException re)…

The correct answer is C. A runtime error is thrown in the thread "main". Option C is correct because the while(true) loop endlessly adds strings to myList, eventually exhausting heap memory and throwing an OutOfMemoryError. Crucially, OutOfMemoryError extends Error - not Exception - so it sits on a completely separate branch of the Throwable…

Handling Exceptions

Question

Given the code fragment: public static void main(String[] args) { ArrayList myList = new ArrayList(); String[] myArray; try { while (true) { myList.add("My String"); } } Catch (RuntimeException re) { System.out.println("Caught a RuntimeException"); } Catch (Exception e) { System.out.println("Caught an Exception"); } System.out.println("Ready to use"); } What is the result?

Options

  • AExecution terminates in the first catch statement, and caught a RuntimeException is printed to the console.
  • BExecution terminates in the second catch statement, and caught an Exception is printed to the console.
  • CA runtime error is thrown in the thread "main".
  • DExecution completes normally, and Ready to use is printed to the console.
  • EThe code fails to compile because a throws keyword is required.

How the community answered

(45 responses)
  • A
    7% (3)
  • B
    20% (9)
  • C
    62% (28)
  • D
    2% (1)
  • E
    9% (4)

Explanation

Option C is correct because the while(true) loop endlessly adds strings to myList, eventually exhausting heap memory and throwing an OutOfMemoryError. Crucially, OutOfMemoryError extends Error - not Exception - so it sits on a completely separate branch of the Throwable hierarchy and slips past both catch blocks uncaught, crashing the thread.

Why the distractors fail:

  • A & B are wrong because neither catch(RuntimeException) nor catch(Exception) covers Error subclasses; only a catch(Throwable) or catch(Error) would intercept it.
  • D is wrong because the loop has no exit condition and the OOM error is never handled, so "Ready to use" is never reached.
  • E is wrong because throws is only required for checked exceptions; Error subclasses are unchecked and require no declaration. (Note: the capitalized Catch in the listing would also be a compile error in real Java, but the exam intends lowercase catch.)

Memory tip: Think of Java's exception hierarchy as a tree with two main branches under Throwable - Exception (catchable program problems) and Error (serious JVM-level failures). A catch(Exception e) is a wide net, but it still has a hole: anything extending Error falls right through it.

Topics

#exception hierarchy#uncaught errors#OutOfMemoryError#try-catch blocks

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice