Skip to content
Ameen Abozaid
Planned lessonJNR-026-L04

Exception translation

  • Lesson 4 of 5
  • Junior
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

  • SQLException is checked and database-specific (error codes, SQL states).
  • Spring catches it and rethrows an unchecked DataAccessException subclass, for example DuplicateKeyException, 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 DataAccessException everywhere.
  • Unhandled ones go to the global exception handler.
Draft outline details

Demonstration

java
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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.