adam bien's blog

Unchecked Exceptions are o.k, checked exceptions for services often better... 📎

With unchecked (subclasses of the java.lang.RuntimeException) you can develop significantly faster. You simply do not have to care about throwing, catching - just writing your code and that is... But is your code also robust?

Most of the .NET/Java EE applications are built with a simple facade, which manages business and persistent objects.
The facade is exposed as the "public" interface of a component and can be also considered as a SOA service. This business interface is often derived from use cases, or other functional specifications or, of course, unit tests.
If you like to specificy use cases in efficient way, it is a good idea to capture the pre- and postconditions. What happens, if the preconditions are not met? An business exception has to be thrown in this case...
Sample:
   public void buyBook() throws NotEnoughMoneyException;
I expect from the analyst, or someone who specifies or realizes the requirements, to list all business errors. I use the names of the errors as an input to create checked exceptions.
It is also possible to declare RuntimeExceptions, but it is very unlikely, that every developer in a mid-size project will do this, in case the compiler do not force him.
Some reasons, why I like checked exceptions as manifestation of business problems (or precondition violation):
  1. Traceability: you just pick the name from the requirements and convert them in exceptions. I generated once even sourcecode from excel-sheets using jxl for this purpose.
  2. Robustness: checked exception has to be catched - but also tested! So developers are forced to catch the exception in JUnit and so test them. It is even better in JUnit 4.0 - you can declare the expected exceptions.
  3. Simplicity/Documentation: the presentation tier developer sees the exceptions in JavaDoc and signature, so it is easier to react to the business errors. The checked exceptions even enrich the signature of the service.
  4. Encapsulation: runtime exceptions can violate the encapsulation, because the service client has to know the realization of the service. Checked exceptions are declared - so it is not needed to know the implementation.
  5. Service Orientation: java interface with checked exceptions can be easily converted in a JMS, SOAP, JXTA, JINI etc. message. You need only a lean adapter/decorator which catches the exceptions and converts them into the appropriate protocol. You can even generate this stuff.
So checked exceptions are far better suitable for coarse grained, business services. Unchecked exceptions are also o.k., but they are optional. So in even mid-size projects they will be probably not used, declared and catched by every developer everytime...(we should be realistic :-))
---advert---:-)
I described errohandling and exceptions more deeply in my (caution: german :-))  book "Enterprise Architekturen".