Question

I am trying to catch a specific exception using MySQL in Java. However, it is running the catch (SQLException ex) instead of the one I want it to.

catch (MySQLIntegrityConstraintViolationException ex) {
}
catch (SQLException ex) {
}

Getting the following error, I would expect it to run the catch (MySQLIntegrityConstraintViolationException ex) function.

11:12:06 AM DAO.UserDAO createUser
SEVERE: null
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'idjaisjddiaij123ij' for key 'udid'

Why is it running catch (SQLException ex) instead of catch (MySQLIntegrityConstraintViolationException ex)?

Was it helpful?

Solution 2

Yes MySQL always thow and catch the SQLException in the execution method. what you have to do is to catch the SQLException in your execution method, them throw new MySQLIntegrityConstraintViolationException

public void executeQuery() {
    try {
        // code
        rs = pstmt.executeQuery();
} catch (SQLException ex) {
   throw new MySQLIntegrityConstraintViolationException(ex);
}

so in the outer method that called the execute method, it should catch only the MySQLIntegrityConstraintViolationException

catch (MySQLIntegrityConstraintViolationException ex) {
   //handle ex
}

OTHER TIPS

Make sure you use correct namespace. For me that one on image attached works like a charm.

Correct namespace

I suggest to use ex instanceof MySQLIntegrityConstraintViolationException to make sure no other exception is thrown as a MySQLIntegrityConstraintViolationException since SQLException can be thrown for many different reasons.

Please import

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

I tested and it will work.

I had the same problem, and I had to show by a JOptionPane message the kind of error to the user. This is my solution

public boolean executeQuery() {
try {
        // code
        rs = pstmt.executeQuery();
} catch (SQLException ex) {
   int errCode = ex.getErrorCode();
     if(errCode == 1062){ //MySQLIntegrityConstraintViolationException 
     JOptionPane.showMessageDialog(null, "Duplicate entry for id.\n");}
     return false;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top