Catching the wrong exception
error-handling, exception, java, mysql
Solution
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
}
Problem
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)`?