Exception translation
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
understand why you get DataAccessException instead of SQLException.
Planned topics
SQLExceptionis checked and database-specific (error codes, SQL states).- Spring catches it and rethrows an unchecked
DataAccessExceptionsubclass, for exampleDuplicateKeyException,DataIntegrityViolationException,EmptyResultDataAccessException. - This keeps services independent of the database and of JDBC.
- Catch a specific subclass at one place that can act (for example turn a duplicate into 409); do not catch
DataAccessExceptioneverywhere. - Unhandled ones go to the global exception handler.
Draft outline details
Demonstration
try {
jdbc.sql("insert into product(sku, name) values (:sku, :name)")
.param("sku", sku).param("name", name).update();
} catch (DuplicateKeyException e) {
throw new SkuAlreadyExistsException(sku);
}Check your understanding
Is DataAccessException checked or unchecked?
Show answer
Unchecked.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.