1Z0-809 · Question #130
Given the code fragment: class X { public void printFileContent () { / code goes here / throw new IOException(); } public class Test { public static void main (String [] args) { X xobj = new X()…
The correct answer is A. Replace line 5 with public void printFileContent () { throws IOException (. Option A is necessary because IOException is a checked exception - Java requires any method that throws one to either catch it in a try-catch block or explicitly declare it with throws IOException in the method signature. Without this declaration on printFileContent(), the…
Question
Options
- AReplace line 5 with public void printFileContent () { throws IOException (
- BReplace line 11 with public static void main (String [] args) throws Exception (
- CAt line 14, insert throw new IOException ();
- DReplace line 7 with throw IOException ("Exception raised");
How the community answered
(17 responses)- A71% (12)
- B18% (3)
- C6% (1)
- D6% (1)
Explanation
Option A is necessary because IOException is a checked exception - Java requires any method that throws one to either catch it in a try-catch block or explicitly declare it with throws IOException in the method signature. Without this declaration on printFileContent(), the compiler rejects the code outright.
Critically, B is also required - the listed answer of "A only" is incomplete. Even after fixing printFileContent(), main() calls that method and inherits the obligation to handle the checked exception. Adding throws Exception (or throws IOException) to main()'s signature satisfies this. Both A and B together produce a compilable result.
Why the distractors fail:
- C is irrelevant -
printFileContent()already throwsIOExceptionon line 7; inserting another throw at the call site inmain()doesn't fix the missing signature declarations. - D is a syntax error -
throw IOException("...")is missing thenewkeyword and uses the wrong constructor call form; it would not compile.
Memory tip: Think of checked exceptions as a contract - every method in the call chain must either handle it (try-catch) or pass it up (throws declaration). When you see a checked exception thrown inside a method, trace the chain upward: every caller also needs to sign the contract until someone catches it.
Community Discussion
No community discussion yet for this question.