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…
Question
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)- A7% (3)
- B20% (9)
- C62% (28)
- D2% (1)
- E9% (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)norcatch(Exception)coversErrorsubclasses; only acatch(Throwable)orcatch(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
throwsis only required for checked exceptions;Errorsubclasses are unchecked and require no declaration. (Note: the capitalizedCatchin the listing would also be a compile error in real Java, but the exam intends lowercasecatch.)
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
Community Discussion
No community discussion yet for this question.