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 St开发者_JAVA技巧ring 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);
}
}
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.
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.
精彩评论