tags:

views:

90

answers:

1

I’ve been surprised by how hard it is to find best practices for this on the web since it must be such a common problem.

App is based on Java 1.5 – JSF 1.2 with Faclets, Seam, JPA, Hibernate. Some Web Service calls. Some JMS.

I’m after general recommendations for Exception handling. There are roughly 3 approaches I’ve seen used but I’ve never been that sure which one is better. Assuming you can’t recover from an error do you: 1) Log the error when it occurs and re-throw it?
2) Log it when it occurs and throw some sort of generic exception?
3) Let it bubble up and then handle it in a generic exception handling servlet or similar.

I’ve tended to use option 2 on previous systems where the architecture has been fairly simple – an adaptor layer talking to various 3rd party systems throws and adaptor exception if it gets an error back and so on. We can display a nice clean message to the user on the screen and keep the details in a log. Here though the architecture is a lot more complex and I’m wondering how well it would work in practice. So I’m interested to know what you prefer and why.

+1  A: 

Assuming you can’t recover from an error...

Assuming this error is not a functional error, I log the error and wrap the exception in an (custom) unchecked exception and let the framework/container handle it (so option 2). I like to do it his way because:

  • I like to use container managed transactions and I want the container to do its job (i.e. rollback any transaction) so throwing a runtime exception is the way to go.
  • It minimize the exception handling work.
  • It make the reporting to the user easy to handle in a generic way.

If it's a functional error (i.e. an alternative flow in a use case), I log the error and wrap the exception in a (custom) checked exception because I want the caller to handle it specifically as the problem is part of the use case.

In both case, I use a root exception for each hierarchy, namely TechnicalException and FunctionalException.

Pascal Thivent
Thanks for your response. Anyone got any other opinions on this?
charles
@charles Pretty surprising to see only one answer here, I was expecting lots of them.
Pascal Thivent
Yes - I'm surprised to. It is a good answeer though so maybe we've put everyone off! Actually the method I see most often when I do code audits is 3 - Let it bubble up and then handle it in a generic exception handling servlet or similar - though it probobly doens't consitute best practice.
charles
@charles If I can't recover from an error, I prefer to wrap it in an unchecked exception so that it can bubble *transparently* (the callers don't have to add the `throws`).
Pascal Thivent