Reputation: 11374
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)
?
Upvotes: 4
Views: 9447
Reputation: 1
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;
}
Upvotes: 0
Reputation: 8023
Make sure you use correct namespace. For me that one on image attached works like a charm.
Upvotes: 6
Reputation: 9
Please import
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
I tested and it will work.
Upvotes: 0
Reputation: 2371
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.
Upvotes: 1
Reputation: 8657
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
}
Upvotes: 2