morbidCode morbidCode - 11 months ago 40
SQL Question

Checking sql errors/exceptions

When I use java, I've often seen code like this:

try {
// any CRUD operation
} catch(SQLException e) {
// do some specific database error stuff
// if we're in a transaction, we usually rollback
try {
// rollback the transaction
} catch(anotherException e) {
// do some specific rollback error stuff

I only encountered sql/database errors when there are things very wrong with my code. Doing SQL operations and putting try catches around them seems very very repetitive.

Since it is good practice to validate user input on the server side, what is the need for catching database exceptions besides connecting to the database at the start of your application?


When accessing any external software system, you should be checking for errors this is just good practice. Although "normal" operations may not generate an error, you can get errors for other reasons. For example:

  • The database server drops the connection.
  • The database/schema/table is no longer available.
  • The query generates a time-out.
  • The database log is full.

You can also get errors if the underlying database changes. For instance:

  • Column types might change.
  • Column names might change.
  • Table names might change.

The point is: Either you are writing throw-away, one-time code or you are writing sustainable code. If the latter, then you should be checking for potential errors. The try/catch blocks are a sign of responsible programming and good practice. They are not clutter.