问题
My Swing applications throws few exceptions. I tried to catch Integrity Constraint Violation Exception and display message "Duplicate ID". But when that happened, without catching it here: catch(MySQLIntegrityConstraintViolationException ex) it goes to catch (SQLException ex). What I want to do is, catch Integrity Violation exception and display user friendly message instead of technical message comes from ex.getMessage(). How do I do this?
ShippmentTransfer shipTrns = new ShippmentTransfer(shipID, GIN, issueDate, ToStore, itemName, Qty, Driver, Vehicle);
int res = ShipmentTansController.addShipGIN(shipTrns);
if (res > 0) {
JOptionPane.showMessageDialog(null, "Record Added");
resetAll();
}
} catch (DataIntegrityViolationException ex) {
JOptionPane.showMessageDialog(null, "Duplicate ID");
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.gets);
}
}
回答1:
In order to catch specific SQLException, need to compare against SQl State using getSQLState() method. Ex: SQl State 23 for Data Integrity violation.
catch (SQLException ex) {
if (ex.getSQLState().startsWith("23")) {
JOptionPane.showMessageDialog(null, "Duplicate");
}
}
Found from here
回答2:
you can not use
MySQLIntegrityConstraintViolationException directly.
Because no exception available in java with that name.
try this
try {
}
catch (DataIntegrityViolationException ex) {
.....
}
and then get the error code using ex.Then compare it
回答3:
For those checking later, you might either choose to check instance type as:
try {
...
} catch (Exception e) {
if (e instanceof SQLIntegrityConstraintViolationException) {
// duplicate record or alike problem
}
}
来源:https://stackoverflow.com/questions/15894455/java-mysql-integrity-constraint-violation-exception