1Z0-829 · Question #46
Given: ``java public class StockException extends Exception { public StockException(String s) { super(s); } } public class OutofStockException extends StockException { public…
The given code is a try-with-resources statement that declares a resource of type AutoCloseable. The resource is an anonymous class that implements the AutoCloseable interface and overrides the close() method. The code also has a print() method that prints the value of the…
Question
public class StockException extends Exception {
public StockException(String s) { super(s); }
}
public class OutofStockException extends StockException {
public OutofStockException(String s) { super(s); }
}
and the code fragment:
public class Test {
public static void main(String[] args) throws OutofStockException {
m();
}
public static void m() throws OutofStockException {
try {
throw new StockException("Raised.");
} catch (Exception e) {
throw new OutofStockException(e.getMessage());
}
}
}
Which statement is true?Explanation
The given code is a try-with-resources statement that declares a resource of type AutoCloseable. The resource is an anonymous class that implements the AutoCloseable interface and overrides the close() method. The code also has a print() method that prints the value of the variable s. The code is supposed to print "Open Close", but it does not compile because of two errors. The first error is at line n1, where the anonymous class is missing a semicolon at the end of its declaration. This causes a syntax error and prevents the code from compiling. To fix this error, option B adds a semicolon after the closing curly brace of the anonymous class. The second error is at line n2, where the print() method is called without an object reference. This causes a compilation error because the print() method is not static and cannot be invoked without an object. To fix this error, option E adds an object reference to the print() method by using the variable t. Therefore, options B and E are correct and enable the code to print "Open Close".
Topics
Community Discussion
No community discussion yet for this question.