Catching the wrong exception

I am trying to catch a specific exception using MySQLin Java. However, it launches catch (SQLException ex)instead of the one I want.

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

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

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

Why does it work catch (SQLException ex)instead catch (MySQLIntegrityConstraintViolationException ex)?

+3
source share
5 answers

Yes, MySQLalways forget and catch SQLExceptionin the execution method. you need to catch SQLExceptionin your execution method, they throw a new oneMySQLIntegrityConstraintViolationException

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

therefore, in an external method called the execute method, it should only catch MySQLIntegrityConstraintViolationException

catch (MySQLIntegrityConstraintViolationException ex) {
   //handle ex
}
+2
source

, . , .

Fix namespace

+6

ex instanceof MySQLIntegrityConstraintViolationException, MySQLIntegrityConstraintViolationException, SQLException .

+1

,

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

, .

0

, JOptionPane .

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

All Articles