Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch a specific exception in JDBC?

Tags:

java

jdbc

How to catch specific exceptions in JDBC? Examples: primary key exception or foreign key exception.

like image 967
GuruKulki Avatar asked Jan 01 '10 13:01

GuruKulki


People also ask

How do you catch an exception in Java?

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.

What are the exceptions of JDBC?

There are two subclasses of this class that are be the standard exceptions that JDBC throws. These subclasses are DB2DBException. java and DB2JDBCException. java.

Can we catch SQL exception?

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.


1 Answers

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:

  • 02: no data
  • 07: dynamic SQL error
  • 08: connection exception
  • 0A: feature not supported
  • 21: cardinality violation
  • 22: data exception
  • 23: integrity constraint violation
  • 24: invalid cursor state
  • 25: invalid transaction state
  • 26: invalid SQL statement name
  • 28: invalid authorization specification
  • 2B: dependent privilege descriptors still exist
  • 2C: invalid character set name
  • 2D: invalid transaction termination
  • 2E: invalid connection name
  • 33: invalid SQL descriptor name
  • 34: invalid cursor name
  • 35: invalid condition number
  • 3C: ambiguous cursor name
  • 3D: invalid catalog name
  • 3F: invalid schema name

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");
}
like image 173
BalusC Avatar answered Oct 12 '22 22:10

BalusC