Should method in data access object (DAO) throw or catch its exception?

Artegon picture Artegon · Mar 5, 2013 · Viewed 11.7k times · Source

I have a Java method in data access object. This very simple method inserts two integer values into database.

public void saveHourMin(int hour, int min) throws SQLException{
psInsert.setInt(1, hour);
psInsert.setInt(2, min);
psInsert.executeUpdate();
}

Should this method, or, generally speaking, any DAO method, throw an exception when SQLException is thrown, or should it catch and log the exception, then inform a user via return code? Which is the right approach for an application using Spring?

Answer

Nathan Hughes picture Nathan Hughes · Mar 5, 2013

You can't count on the caller to consistently check return codes, you are better off throwing an exception.

If you throw SQLException then that will be messy, you will probably end up with higher layers either adding "throws Exception" on every method, or just eating exceptions. Neither one of those alternatives are good.

The way Spring does it is it supplies an exception translator that takes in the original SQLException and throws a subclass of RuntimeException that includes the original SQLException as a cause and which tries to give as much information about the error as possible, including using vendor error codes to decide which specific subclass to throw. If you utilize any of Spring's jdbcTemplates then you get the exception translation functionality, so you won't need to include any exception-catching or throwing in your data access objects.

If you don't want to use Spring, you can catch the SQLException inside the DAO and throw a RuntimeException, including the original SQLException as a cause. There is nothing you can do about most SQLExceptions, you just want to fail fast and get the exception logged.