Catching the wrong exception

。_饼干妹妹 提交于 2019-12-10 19:39:32

问题


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


回答1:


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
}



回答2:


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




回答3:


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.




回答4:


Please import

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

I tested and it will work.




回答5:


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;
}


来源:https://stackoverflow.com/questions/21904707/catching-the-wrong-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!