Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataAccessException vs SQLException

I have two questions related to exception handling in Spring framework.

  1. Why is Spring framework's DataAccessException a runtime exception whereas core Java's SQLException a checked exception?

  2. What advantage does Spring's exception handling offers over Java's exception handling mechanism?

like image 561
Nital Avatar asked Jan 09 '15 21:01

Nital


People also ask

What is the DataAccessException?

Class DataAccessExceptionThis exception hierarchy aims to let user code find and handle the kind of error encountered without knowing the details of the particular data access API in use (e.g. JDBC). Thus, it is possible to react to an optimistic locking failure without knowing that JDBC is being used.

What are the subclasses of DataAccessException?

Hibernate-specific subclass of DataAccessException, for JDBC exceptions that Hibernate rethrew. Hibernate-specific subclass of ObjectRetrievalFailureException. Hibernate-specific subclass of ObjectOptimisticLockingFailureException.

What are the exceptions thrown by the Spring DAO classes?

Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception.

How do I instantiate DataAccessException?

DataAccessException is an abstract class and can not be instantiated. Instead use one of the concrete classes such as new DataRetreivalFailureException("this was the reason") or create your own: throw new DataAccessException("this was the reason") {}; And you get an anonymous class derived from the DataAccessException.


1 Answers

The reason to use DataAccessException over SQLException is that it more generally describes the problem. If you have a Repository or DAO interface that has two different implementations, one for Oracle and one for Cassandra, you can have this one exception express failures for both implementations.

As for why this is Runtime and not a checked exception, it allows the callers to not have to explicitly handle it. It seems in my experience that if an SQLException or DataAccessException is thrown there's not much I can or want to do about it other than let it bubble up to somebody that can. Having to declare the throwables at each layer is more burden on the caller. If one of them cares to catch and handle it, they can.

Here are the JavaDocs (thanks @Tom!)

  1. DataAccesssException
  2. SQLException
like image 138
Todd Avatar answered Oct 08 '22 00:10

Todd