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...
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):
- 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.
- 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.
- 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.
- 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.
- 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.
I described errohandling and exceptions more deeply in my (caution: german :-)) book "Enterprise Architekturen".
Cloudy Jakarta EE and MicroProfile: Microservices, Clouds and Beyond Jakarta EE / MicroProfile airhacks workshops at MUC airport, Winter Edition
airhacks.fm the podcast:
Stay in touch: airhacks.news.