Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 26
Question ID: UKOCP22518
Given code of Test.java file:
- package com.udayankhattry.ocp;
- import java.sql.SQLException;
- public class Test {
- private static void checkData() throws SQLException {
- try {
- throw new SQLException();
- } catch (Exception e) {
- e = null; //Line n1
- throw e; //Line n2
- }
- }
- public static void main(String[] args) {
- try {
- checkData(); //Line n3
- } catch(SQLException e) {
- System.out.println("NOT AVAILABLE");
- }
- }
- }
What will be the result of compiling and executing Test class?
- A NOT AVAILABLE is printed on to the console and program terminates successfully
- B Program ends abruptly
- C Line n1 causes compilation failure
- D Line n2 causes compilation failure
- E Line n3 causes compilation failure
Reveal correct answer
Correct answer: D
Explanation
UKOCP22518:
Exception is a java class, so e = null; is a valid statement and compiles successfully.
If you comment Line n1, and simply throw e, then code would compile successfully as compiler is certain that 'e' would refer to an instance of SQLException only.
But the moment compiler finds e = null;, throw e; (Line n2) causes compilation error as at runtime 'e' may refer to any Exception type.
NOTE: No issues with Line n3 as method checkData() declares to throw SQLException and main(String []) method code correctly handles it.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
