Alex Abdugafarov
Alex Abdugafarov

Reputation: 6412

How to properly catch, wrap and re-throw a Hibernate exceptions?

My database worker is implemented above the Hibernate. If something goes wrong, it's methods should rollback the transaction and throw an SQLException. So my question is: what is the best (i.e. cleanest) way to handle Hibernate exceptions? Currently all my methods looks as ugly as this:

public EntryUserHib addUser(final String username, final String pwdhash) throws SQLException{
    try {
        final Transaction ta = sess.beginTransaction();
        try {
            // Using Hibernate here
            // "return" statement
        } catch(final HibernateException ex) {
            try {
                ta.rollback();
            } catch(final Exception ex1) {}
            throw ex;
        } finally {
            if (!ta.wasRolledBack()) ta.commit();
        }
    } catch(final HibernateException ex) {
        if (ex.getCause() != null) {
            if (ex.getCause() instanceof SQLException) throw (SQLException)ex.getCause();
            throw new SQLException(ex.getCause());
        }
        throw new SQLException(ex);
    }
}

Upvotes: 3

Views: 17637

Answers (2)

Ryan Stewart
Ryan Stewart

Reputation: 128839

Let someone else manage it for you, like Spring. It has extensive Hibernate and transaction support that will extract all of that code that you're worried about.

Upvotes: 2

RichW
RichW

Reputation: 2024

Don't catch them at all. Hibernate exceptions extend RuntimeException for two good reasons: you don't have to declare them in method signatures, and any RuntimeException automatically causes a rollback of the transaction. Exception-handling makes for very cluttered code. The Hibernate folks have the philosophy that HibernateExceptions should be fatal errors, signaling coding or logic errors, and in a properly-function application should not be (and doesn't need to be) caught.

Your application's UI should respond to these surprises in a user-friendly way, though. That's a separate issue.

Upvotes: 3

Related Questions