Given: class ImageScanner implements AutoCloseable { public void close () throws Exception { System.out.print ("Scanner closed."); } public void scanImage () throws Exception { System.out.print ("Scan."); throw new Exception("Unable to scan."); } } class ImagePrinter implements AutoCloseable { public void close () throws Exception { System.out.print ("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?
Click on the arrows to vote for the correct answer
A. B. C. D.A.
The code creates two resources, ImageScanner
and ImagePrinter
, both of which implement AutoCloseable
. In the try
block, the resources are instantiated within the parentheses, which means that they will be automatically closed when the block is exited, regardless of whether there is an exception or not.
The first resource, ImageScanner
, has a method scanImage()
that prints "Scan." to the console and throws a new Exception
with the message "Unable to scan." The second resource, ImagePrinter
, has a method printImage()
that prints "Print." to the console.
Since scanImage()
throws an exception, it is caught by the catch
block, which prints the exception message to the console using getMessage()
.
Since the ImageScanner
resource is the first to be instantiated, its close()
method is called first when the try
block is exited. This prints "Scanner closed." to the console.
Similarly, when the try
block is exited, the close()
method of the ImagePrinter
resource is called, which prints "Printer closed." to the console.
Putting it all together, the output of the program is:
Scan.Printer closed. Scanner closed. Unable to scan.
Therefore, the correct answer is option A.