Nital
Nital

Reputation: 6084

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?

Upvotes: 24

Views: 39862

Answers (1)

Todd
Todd

Reputation: 31700

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

Upvotes: 20

Related Questions