1Z0-809 · Question #111
Given the class definitions: ``java class ImageScanner implements AutoCloseable { public void close () throws Exception { System.out.println ("Scanner closed."); } public void scanImage () throws…
The correct answer is C. Scan.Print.Printer closed.Scanner closed.Unable to scan. There is actually an error in the stated correct answer. Based on Java's try-with-resources semantics, A is the correct answer, not C. Here is why: Why A is correct: ir.scanImage() prints "Scan." and then immediately throws an exception. Because the exception is thrown, the…
Question
class ImageScanner implements AutoCloseable {
public void close () throws Exception {
System.out.println ("Scanner closed.");
}
public void scanImage () throws Exception {
System.out.println ("Scan.");
throw new Exception ("Unable to scan.");
}
}
And:
class ImagePrinter implements AutoCloseable {
public void close () throws Exception {
System.out.println ("Printer closed.");
}
public void printImage () {System.out.print ("Print.");}
}
And this code fragment:
try (
ImageScanner ir = new ImageScanner();
ImagePrinter iw = new ImagePrinter() ) {
ir.scanImage();
iw.printImage();
} catch (Exception e) {
System.out.print (e.getMessage());
}
What is the result?Options
- AScan.Printer closed.Scanner closed.Unable to scan.
- BScan.Print.Unable to scan.Printer closed.Scanner closed.
- CScan.Print.Printer closed.Scanner closed.Unable to scan.
- DCompilation fails
How the community answered
(49 responses)- A2% (1)
- B4% (2)
- C82% (40)
- D12% (6)
Explanation
There is actually an error in the stated correct answer. Based on Java's try-with-resources semantics, A is the correct answer, not C.
Here is why:
Why A is correct: ir.scanImage() prints "Scan." and then immediately throws an exception. Because the exception is thrown, the next statement iw.printImage() is never reached - execution exits the try block. Try-with-resources then automatically closes resources in reverse order of declaration: iw.close() fires first ("Printer closed."), then ir.close() ("Scanner closed."). Finally, the catch block prints "Unable to scan." (no newline, since it uses print not println).
Why the other options fail:
- B and C both show "Print." in the output, which requires
iw.printImage()to execute - impossible since the exception fromscanImage()aborts the try block before that line. - B additionally puts the catch output before the resource closes, which contradicts the try-with-resources spec: resources always close before the catch body runs.
- D fails because the code is syntactically and semantically valid Java.
Memory tip: In try-with-resources, think "throw = emergency exit." The moment an exception is thrown in the try block, execution stops there, resources auto-close in reverse open-order (LIFO), and only then does the catch block run. "Close before catch, reverse of open."
Community Discussion
No community discussion yet for this question.