6/12/2007

Centralize exception handling in java methods

Oftentimes we need to handle a series of java exceptions in one method in a similar manner. So it's desirable to centralize the exception logic to avoid duplication. For example, the following method looks up UserTransaction and then performs the transaction. You will need to handle at least 6 exceptions. I find it handy to first save the exception to handle it at the end.

    public void transaction2() throws AppException {
Exception savedException = null;
//1. lookup UserTransaction
UserTransaction ut = null;
try {
Context ic = new InitialContext();
ut = (UserTransaction) ic.lookup("java:comp/UserTransaction");
} catch (NamingException ex) {
savedException = ex;
}

//2. perform transaction
if(ut != null) {
try {
ut.begin();
//...
ut.commit();
} catch (NotSupportedException ex) {
savedException = ex;
} catch (IllegalStateException ex) {
savedException = ex;
} catch (SecurityException ex) {
savedException = ex;
} catch (HeuristicMixedException ex) {
savedException = ex;
} catch (SystemException ex) {
savedException = ex;
} catch (HeuristicRollbackException ex) {
savedException = ex;
} catch (RollbackException ex) {
savedException = ex;
}
}
if(savedException != null) {
//log it, etc, etc
throw new AppException(savedException);
}
}