Skip to content

How to catch a specific exception in JDBC?

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


SQLException contains some database-specific info related to the exception. From the doc:

Each SQLException provides several kinds of information:

1) a string describing the error. This is used as the Java Exception message, available via the method getMesage.

2) a “SQLstate” string, which follows either the XOPEN SQLstate conventions or the SQL 99 conventions. The values of the SQLState string are described in the appropriate spec. The DatabaseMetaData method getSQLStateType can be used to discover whether the driver returns the XOPEN type or the SQL 99 type.

3) an integer error code that is specific to each vendor. Normally this will be the actual error code returned by the underlying database.

4) a chain to a next Exception. This can be used to provide additional error information.