Java OCA OCP Practice Question 2235

Question

Consider the following program:

import java.sql.SQLException;

class CustomSQLException extends SQLException {}

class BaseClass {
     void foo() throws SQLException {
         throw new SQLException();
   }//from   ww  w  . ja  v  a2 s. c o  m
}

class DeriClass extends BaseClass {
     public void foo() throws CustomSQLException {           // LINE A
         throw new CustomSQLException();
   }
}

public class Main {
     public static void main(String []args) {
         try {
             BaseClass base = new DeriClass();
             base.foo();
         } catch(Exception e) {
             System.out.println(e);
     }
   }
}

Which one of the following options correctly describes the behavior of this program?

A.  the program prints the following: SQLException
B.  the program prints the following: CustomSQLException
C.  the program prints the following: Exception
d.  When compiled, the program will result in a compiler 
    error in line marked with comment Line a due to incompatible 
    throws clause in the overridden foo method


B.

Note

the exception thrown is CustomSQLException object from the overridden foo method in DeriClass.

note that SQLException is a checked exception since it extends the exception class.

inside the BaseClass, the foo method lists SQLException in its throws clause.

in the DeriClass, the overridden foo method lists CustomSQLException in its throws clause: it is acceptable to have a more restrictive exception throws clause in a derived class.

hence, the given program compiles successfully and prints CustomSQLException.




PreviousNext

Related