Tuesday, 27 January 2009

Throwing an exception vs returning null

Recently I came across the following problem: How should the callee report a rejection/failure to the caller? I'm writing about the Java components such as business logic services, repositories, etc. Our applications are full of them, thus it should be clear to everybody how to deal with this problem. I can suggest the following possibilities:
  1. Throw checked exception,
  2. Throw unchecked exception,
  3. Return null,
  4. Return some extra error-indicating object.
So, which one should I use? In my opinion only the answers 2 and 4 are correct. However, surprisingly in the last few days I heard from two other Java guys, that I should return a null. In this concrete case the service is a stateless converter which transforms back and forth between the XML message and domain objects. Although the message is well formed and valid the converter may not be able to transform the message, because the transformation is content dependant. Should it then return null or throw an exception? They say it should return null because throwing an exception forces the caller to control the flow with the exceptions. I disagree with that, because from the converter point of view the data it gets is unknown and has to be rejected. The rejection should be reported as an unchecked exception with the exact reason inside. Then the caller can catch the exception and take further steps, or more probably let it bubble up to the MDB and be resolved there.