The answer is B because the code fragment contains a syntax error that prevents it from compiling. The code fragment tries to catch a StockException in line 10, but the catch block does not have a parameter of type StockException. The catch block should have a parameter of type StockException, such as:
catch (StockException e) { // handle the exception }
This is required by the Java syntax for the catch clause, which must have a parameter that is a subclass of Throwable. Without a parameter, the catch block is invalid and causes a compilation error.
Option A is incorrect because the program does not throw a StockException, as it does not compile.
Option C is incorrect because the program does not throw an OutofStockException, as it does not compile.
Option D is incorrect because the program does not throw a ClassCastException, as it does not compile. References:
Oracle Certified Professional: Java SE 17 Developer
Java SE 17 Developer
OCP Oracle Certified Professional Java SE 17 Developer Study Guide
The try-with-resources Statement (The Java™ Tutorials > Essential Classes > Exceptions)
The catch Blocks (The Java™ Tutorials > Essential Classes > Exceptions)
Question 2
Given the code fragment:
Which action enables the code to compile?
Options:
A.
Replace record with void.
B.
Remove the regNO initialization statement.
C.
Make the regNo variable static.
D.
Replace thye regNo variable static
E.
Make the regNo variable public
Answer:
E
Explanation:
Explanation:
The code will compile if the regNo variable is made public. This is because the regNo variable is being accessed in the main method of the App class, which is outside the scope of the Product class. Making the regNo variable public will allow it to be accessed from outside the class. References:
Question 3
Given the code fragments:
Which action prints Wagon : 200?
Options:
A.
At line n1, implement the java.io, Serializable interface.
B.
At line n3, replace readObject (0 with readLine().
C.
At Line n3, replace Car with LuxurayCar.
D.
At Line n1, implement the java.io.AutoCloseable interface
E.
At line n2, in the main method signature, add throws IOException, ClassCastException.
F.
At line n2, in the main method signature, add throws IoException, ClassNotFoundException.
Answer:
F
Explanation:
Explanation:
The code fragment is trying to read an object from a file using the ObjectInputStream class. This class throws an IOException and a ClassNotFoundException. To handle these exceptions, the main method signature should declare that it throws these exceptions. Otherwise, the code will not compile. If the main method throws these exceptions, the code will print Wagon : 200, which is the result of calling the toString method of the LuxuryCar object that was written to the file. References: ObjectInputStream (Java SE 17 & JDK 17) - Oracle, ObjectOutputStream (Java SE 17 & JDK 17) - Oracle