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".


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Hi Adam,

I just wanted to thank you for the excellent blog, filled with pragmanism and experience.
It is so refreshing to read such balanced writing, especially when blogosphere is filled with the usual non-sensical blogs with entries like "Rails will solve all problems", "J2EE will die", "Scripting languages will rule the world", "Agile is the answer to world hunger"...

I just read your blog from start to finish, and immediately placed in my bookmarks. :)

Thanks again. I hope you'll continue your writings.

Posted by Vladimir Sizikov on August 11, 2006 at 12:49 PM CEST #

As for the exceptions...

I thought that I'm the only one who thinks that checked exceptions do have a lot of value.

Yes, sometimes they are an annoyance and force people to think about things like exception handling policy, what to do with exception, etc. It's much more easier and faster to ignore exceptions altogether, if compiler does'n force people to stop and think.

Posted by Vladimir Sizikov on August 11, 2006 at 12:53 PM CEST #

Thank you Vladimir,

Every extreme thing, opinion, thought cannot last and will die.

There are also no silver bullets out there. We all still have to know what we are doing.
Some technologies, languages and frameworks can help us, but I do not understand most of the hypes - and also sometimes "religious" debates what is good and what not.
I see companies wasting money just throwing away mature technologies that work and try to use the next hype.

I only "expose" my opinion and see what happen. I try to learn from comments and feedback :-).

I do not understand the whole discussion about exceptions. Which strategy is used is mostly dependent on the project context and category... There is no general solution - so we will still have enough to in the next time :-)

Thank you again,

adam

Posted by Adam Bien on August 11, 2006 at 01:03 PM CEST #

Vladimir,

the same is valid for loose coupling, scripting languages etc.
In Java the compiler do lot of work, in scripting the developer has to write unit tests to ensure the type safety. So the developer has the choice. But his choice should be not explained by hype, but specific needs :-)

thanks,

adam

Posted by Adam Bien on August 11, 2006 at 01:06 PM CEST #

My main complaint is that it's almost always a bad idea to catch exceptions (and only ignore or log them), and it's also almost always a bad idea to declare exceptions unless you mean that for your own API. So checked exceptions usually have only one good choice: catch, wrap, and throw. So you spend a lot of code just to obfuscate problems.

And it's such a pain (and perhaps non-obvious for newbies), that you often find exceptions just being ignored or logged, and then random error conditions perpetuate through code since expectations are no longer met.

I don't see why this changes for services. You can always declare any exception you want if you want to make it a visible/documented part of your API.

As for hiding implementation, I agree that it's bad practice to catch exceptions that aren't declared. I consider that a design flaw in Java.

Posted by Tom Palmer on August 12, 2006 at 12:37 AM CEST #

Tom,

a service is nothing else, than a business API. In my opinion Exceptions can enrich the interfaces. Catching and logging is not always a good idea. Service-client often knows what to do. In my example :the exception NoEnoughMoneyException be catched in the presentation tier - and another view or form presented. Also an alternate page-flow could be initiated.
But you are right: people often throw just java.lang.Exception -> this is an antipattern.

Posted by Adam Bien on August 12, 2006 at 12:07 PM CEST #

NO NO NO!

Exceptions should NOT be used for business logic.
Period.

THINK! THINK! THINK!

Posted by mv on November 02, 2006 at 01:02 AM CET #

Mv,

thank you for the clear and self-explanatory comment :-).
I do not like to use exceptions for business logic. I'd like to make a difference between system and business errors. Is it better to manifest business errors with return codes? (or back to C)

Posted by Adam Bien on November 03, 2006 at 11:05 AM CET #

I know this post is quite old... But the question remains: How do I tell the view (aka web project) that there was something wrong with the submitted data (that is beyond validation)?

Example:
An administrator can change user information in a LDAP. There is a method in the EJB facade named updateUser(User user). Now the LDAP forces a password policy AND checkes that the username is unique. This are two possible topics that can possibly go wrong - but no exception since I know that those things may happen. Now: Do I use return codes (public ReturnCodeEnum updateUser(User user) ) or do I throw a wrapped exception anyway?

Thanks for your input and this great blog.
Greetings Joe

Posted by Joe on May 06, 2013 at 04:22 PM CEST #

@Joe,

I used "CompositeValidationExceptions" for that. See Page 284 in http://realworldpatterns.com. See GenericDTO pattern (source: https://kenai.com/projects/javaee-patterns/).

It worked well,

thanks!,

adam

Posted by Adam Bien on May 14, 2013 at 11:33 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License