Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching the wrong exception

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)?

like image 730
Patrick Reck Avatar asked Jan 11 '23 04:01

Patrick Reck


2 Answers

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

Correct namespace

like image 181
lukyer Avatar answered Jan 20 '23 13:01

lukyer


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
}
like image 42
Salah Avatar answered Jan 20 '23 14:01

Salah