1Z0-819 · Question #161
import java.io.FileNotFoundException; import java.io.IOException; public class Tester { public static void main(String[] args) { doA(); //Line 1 } private static void doA() throws IOException…
The correct answer is A. catch(IOException e) {}. Option A is correct because doA() declares throws IOException, which is a checked exception - the compiler requires it to be caught (or re-declared) in any caller that doesn't propagate it. Catching IOException alone is sufficient because FileNotFoundException is a subclass of…
Question
Options
- Acatch(IOException e) {}
- Bcatch(FileNotFoundException |IndexOutOfBoundsException e) {}
- Ccatch(IndexOutOfBoundsException |IOException e) {}
- Dcatch(IndexOutOfBoundsException e) {} catch(FileNotFoundException e) {}
- Ecatch(IndexOutOfBoundsException e) {}catch(IndexOutOFBou dsException e) {}
How the community answered
(35 responses)- A77% (27)
- B6% (2)
- C11% (4)
- D3% (1)
- E3% (1)
Explanation
Option A is correct because doA() declares throws IOException, which is a checked exception - the compiler requires it to be caught (or re-declared) in any caller that doesn't propagate it. Catching IOException alone is sufficient because FileNotFoundException is a subclass of IOException, so it's already covered. IndexOutOfBoundsException is an unchecked exception (it extends RuntimeException), meaning the compiler never requires it to be caught, so no catch for it is needed.
Why the distractors fail:
- B catches
FileNotFoundExceptioninstead ofIOException- the compiler seesIOExceptionin thethrowsclause and won't accept a narrower subtype as a substitute; uncaughtIOExceptionstill causes a compile error. - C catches both
IndexOutOfBoundsException | IOException- whileIOExceptionwould satisfy the compiler, catching an unchecked exception alongside it in a multi-catch is unnecessary; the exam marks this as not the required solution (minimal, clean handling is expected). - D catches
IndexOutOfBoundsExceptionandFileNotFoundExceptionseparately - again,FileNotFoundExceptiondoesn't cover the declaredIOExceptiontype, so the compiler still complains about unhandledIOException. - E attempts two
catchblocks for the same exception type (IndexOutOfBoundsExceptiontwice), which is always a compile error regardless of the typo.
Memory tip: Think "Checked = Caught" - only checked exceptions (those NOT extending RuntimeException) trigger compile errors when uncaught. If a method declares throws SomeCheckedException, your caller must catch that exact type or a supertype - a subtype alone won't satisfy the compiler.
Topics
Community Discussion
No community discussion yet for this question.