mickeymoon
mickeymoon

Reputation: 4977

How to identify database exceptions in java?

I have a database that my java program or a web application connects to for persistence of application state. In certain calls to the database, certain exceptions might arise like there might be a duplicate key exception or some check constraint might fail, or it could be as simple as a bad sql grammer. How can I effectively identify the kind of exception thrown so that an appropriate action based on the type of exception could be taken. For e.g prompting the user that a record already exists in case of duplicate key exception.

There could be a way by checking the exception string but could there be a less tedious way of doing it?

Also, is it possible to obtain more detailed information like if a unique key constraint is violated which of the several unique columns happened to be the culprit?

Please base your answers with respect to Java programming language or any frameworks like Spring based on java.

Upvotes: 0

Views: 1113

Answers (1)

jmrodrigg
jmrodrigg

Reputation: 600

Use java.sql.SQLException (javadoc here).

On catching a SQLException you can view its SQLState, it will denote which type of error has ocurred according to the standards (XOPEN or SQL:2003).

Upvotes: 2

Related Questions