Exam 1z0-809 All QuestionsBrowse all questions from this exam
Question 28

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?

    Correct Answer: A

    The scanImage() method in ImageScanner prints 'Scan.' and then throws an exception. Within the try-with-resources statement, both ImageScanner and ImagePrinter implement the AutoCloseable interface, which means their close() methods will be invoked automatically when the block exits. The close() methods are called in reverse order of their creation, so ImagePrinter's close() (which prints 'Printer closed.') is called first, followed by ImageScanner's close() (which prints 'Scanner closed.'). Finally, the exception message 'Unable to scan.' is printed in the catch block. Hence, the output will be: Scan.Printer closed. Scanner closed. Unable to scan.

Discussion
InnovationOption: A

ir.scanImage() prints "Scan." then throws an exception. And because both classes are autoclosable, both close() methods will get invoked, but in reverse oreder, so iw.close() gets invoked, then ir.close() and finally, the exception message is printed so the correct answer is A Scan.Printer closed.Scanner closed.Unable to scan.

adnano1234Option: A

The correct answer is A

DestroyerOption: A

The correct answer is A

asdfjhfgjuaDCVOption: A

A is the correct answer...

steefaandOption: A

Answer is A. scanImage method prints Scan and throws exception which is caught but firstly close methods of resources (in revered order) are called.

r1muka5Option: A

Answer is A

WilsonKKerllOption: A

Answer is A.