How to catch specific exceptions in JDBC? Examples: primary key exception or foreign key exception.
The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.
There are two subclasses of this class that are be the standard exceptions that JDBC throws. These subclasses are DB2DBException. java and DB2JDBCException. java.
An SQLException can occur both in the driver and the database. When such an exception occurs, an object of type SQLException will be passed to the catch clause. Gets the error number associated with the exception.
The best and DB-independent way to handle SQLException
more specifically is to determine the SQL state code which can be obtained by SQLException#getSQLState()
. The SQLState is a 5-char code, of which the first two are common among all DB's and the last three might differ depending on the DB and/or the specific condition. Here's an extract from the spec:
So to determine whether the SQL Exception is caused by a constraint violation, you can just do the following in a (fictive) SQLUtil
class:
public static boolean isConstraintViolation(SQLException e) {
return e.getSQLState().startsWith("23");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With