2

The below snippet code is from Spring 5 Recipes book (page 386). I'm trying to run and test code but get NullPointerException for sqle variable and further seems there is no relation between SQLException and DataAccessException in Spring 5. Can someone tell me why and how?

package com.apress.springrecipes.vehicle;
...
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;

public class Main {

    public static void main(String[] args) {
        ...
        VehicleDao vehicleDao = context.getBean(VehicleDao.class);
        Vehicle vehicle = new Vehicle("EX0001", "Green", 4, 4);
        try {
            vehicleDao.insert(vehicle);
        } catch (DataAccessException e) {
            SQLException sqle = (SQLException) e.getCause();
            System.out.println("Error code: " + sqle.getErrorCode());
            System.out.println("SQL state: " + sqle.getSQLState());
        }
    }
}
2
  • It seems e.getCause() is not of type SqlException. You colud print all stack trace before perform cast operation or use your IDE to debug it. Commented Oct 14, 2018 at 13:51
  • Is your vehicleDao null? Commented Oct 14, 2018 at 14:17

1 Answer 1

1

First of all, you never check if e.getCause() returns null or not. If it returns null your code is vulnerable for NullPointerException

Second point is, why Spring change its way of handling database/jpa exceptions. There are already some conversations about that. For example LINK

Or further you can check out book "Spring in Action" by C. Walls where in chapter about JDBC we can read.

(10.1.1 Getting to know Spring’s data-access exception hierarchy)

On one hand, JDBC’s exception hierarchy is too generic—it’s not much of a hierarchy at all. On the other hand, Hibernate’s exception hierarchy is proprietary to Hibernate. What we need is a hierarchy of data-access exceptions that are descriptive but not directly associated with a specific persistence framework.

I highly recommend whole subchapter to understand this topic.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem. If you think that my answer was helpful please make sure to upvote IT and Mark as a answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.