Java OCA OCP Practice Question 2432

Question

Paul has to modify a method that throws a SQLException when the method can't find matching data in a database.

Instead of throwing a SQLException, the method must throw a custom exception, DataException.

Assuming the modified method is defined as follows, which option presents the most appropriate definition of DataException?.

void accessData(String parameters) {
    try {
        //..code that might throw SQLException
    }
    catch (SQLException e) {
        throw new DataException("Error with Data access");
    }
}

a  class DataException extends Exception {
       DataException() {super();}
       DataException(String msg) { super(msg); }
   }/*ww w.  j a  v  a 2 s  . c o  m*/

b  class DataException extends RuntimeException {
       DataException() {}
       DataException(String msg) {}
   }

c  class DataException {
       DataException() {super();}
       DataException(String msg) { super(msg); }
   }

d  class DataException extends Throwable {
       DataException() {super();}
       DataException(String msg) { super(msg); }
   }


b

Note

Option (a) is incorrect because it defines custom exception DataException as a checked exception.

To use checked DataException, accessData() must specify it to be thrown in its throws clause.

Option (b) is correct because it defines custom exception DataException as an unchecked or runtime exception.

Even though method accessData() throws a DataException, a runtime exception, it need not declare its name in its throws clause.

Option (c) is incorrect.

Class DataException extends class Object and not Exception.

Also, this code won't compile because class Object doesn't define a constructor that matches Object(String).

Option (d) is incorrect.

If DataException extends Throwable, accessData() won't compile because it's also a checked exception and therefore must be handled or declared.




PreviousNext

Related