2

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

3 Answers 3

3

In order to catch a specific SQLException, you 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

Sign up to request clarification or add additional context in comments.

Comments

1

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

7 Comments

Thnx for your response. Then how do I catch the Integrity Constraint Violation Exception? Do you have any idea?
try to get the name of exception using ex.Then compare
try to debug ex when raised the exception.What it contains when IntegrityVoilationException raises and other raised.
Sure. I ll try in that way.
Finally managed to sort it out. I used method getSQLState() produces specific error code. Ex. 23 for Data Integrity violation. if(ex.getSQLState().startsWith("23")){ Anyway I appreciate your effort to help me.
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.