Adam Bien's Weblog

Friday Aug 11, 2006

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


[my tweets]  Rss My book: Real World Java EE - Rethinking Best Practices

Kommentare:

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.

Gesendet von Vladimir Sizikov am August 11, 2006 at 10:49 AM 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.

Gesendet von Vladimir Sizikov am August 11, 2006 at 10:53 AM 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

Gesendet von Adam Bien am August 11, 2006 at 11:03 AM 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

Gesendet von Adam Bien am August 11, 2006 at 11:06 AM 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.

Gesendet von Tom Palmer am August 11, 2006 at 10:37 PM 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.

Gesendet von Adam Bien am August 12, 2006 at 10:07 AM CEST #

NO NO NO!

Exceptions should NOT be used for business logic.
Period.

THINK! THINK! THINK!

Gesendet von mv am November 02, 2006 at 12: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)

Gesendet von Adam Bien am November 03, 2006 at 10:05 AM CET #

Senden Sie einen Kommentar:
  • HTML Syntax: Ausgeschaltet
Meta-stuff / Interviews
My Recent Book
Java One 2009
CommunityOne East N.Y.C
JavaONE 2008 Interview
Search
...the last 150 posts
...the last 10 comments
greenfire.dev.java.net
Links
my.netbeans.org
Visitors
License