The Artima Developer Community
Sponsored Link

Java Community News
Effective Java Exceptions

10 replies on 1 page. Most recent reply: Jan 25, 2007 5:08 AM by Iulian Dragos

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 10 replies on 1 page
Frank Sommers

Posts: 2642
Nickname: fsommers
Registered: Jan, 2002

Effective Java Exceptions Posted: Jan 17, 2007 2:20 PM
Reply to this message Reply
Summary
Typed exceptions have been touted as one of Java's key strengths. Early Java API designers, however, did not always understand the proper role of exceptions, giving developers bad examples of exception handling, according to Barry Ruzek's latest Dev2Dev article. Ruzek presents a framework to help integrate exception handling into an architecture.
Advertisement

Barry Ruzek argues in a recent BEA Dev2Dev article, Effective Java Exceptions, that:

Exception handling in a Java application tells you a lot about the strength of the architecture used to build it... A good way to measure the skill of a Java architect and the development team's discipline is to look at exception handling code inside their application. The first thing to observe is how much code is devoted to catching exceptions, logging them, trying to determine what happened, and translating one exception to another. Clean, compact, and coherent exception handling is a sign that the team has a consistent approach to using Java exceptions...

Ruzek admits that while exceptions are a powerful feature of Java, the designers of the first Java APIs didn't always follow meaningful exception-handling practices. That led to much confusion by developers using those APIs, and even to the notion that checked Java exceptions were a bad idea:

To programmers, it seemed like most of the common methods in Java library classes declared checked exceptions for every possible failure. For example, the java.io package relies heavily on the checked exception IOException. At least 63 Java library packages issue this exception, either directly or through one of its dozens of subclasses...

An I/O failure is a serious but extremely rare event. On top of that, there is usually nothing your code can do to recover from one. Java programmers found themselves forced to provide for IOException and similar unrecoverable events that could possibly occur in a simple Java library method call. Catching these exceptions added clutter to what should be simple code because there was very little that could be done in a catch block to help the situation...

This no-win situation resulted in most of the notorious exception handling anti-patterns we are warned about today. It also spawned lots of advice on the right ways and the wrong ways to build workarounds...

Newer Java APIs such as the Spring Framework and the Java Data Objects library have little or no reliance on checked exceptions. The Hibernate ORM framework redefined key facilities as of release 3.0 to eliminate the use of checked exceptions. This reflects the realization that the great majority of the exception conditions that these frameworks report are unrecoverable, stemming from incorrect coding of a method call, or a failure of some underlying component such as a database server.

Recognizing that some exceptions are part of the expected, albeit rare, outcome of a method invocation, while other exceptions represent errors a client is not expected to recover from, Ruzek presents a simple framework for dealing with exceptions at the architecture level. In one category are what he calls "contingency" exceptions, and in the other category are unplanned failures or faults:

Contingency... is an expected condition demanding an alternative response from a method that can be expressed in terms of the method's intended purpose. The caller of the method expects these kinds of conditions and has a strategy for coping with them.

Fault [is] an unplanned condition that prevents a method from achieving its intended purpose that cannot be described without reference to the method's internal implementation...

Contingencies are expected and natural consequences of using [an] API. They do not represent a failure of the software or of the execution environment. Contrast these with actual failures that could arise due to problems related to the internal implementation details of [a class]...

Ruzek maps contingencies to Java checked exceptions and faults to subclasses of RuntimeException.

How do you integrate exception handling into your architecture?


Howard Lovatt

Posts: 321
Nickname: hlovatt
Registered: Mar, 2003

Re: Effective Java Exceptions Posted: Jan 17, 2007 5:41 PM
Reply to this message Reply
I agree with Barry Ruzek and like his terminology, Contingency and Fault, it is a pity that Java chose Exception and RuntimeException, respectively, as I don't find these terms intuitive. Barry's advice is essentially the same as Joshua Bloch's in Effective Java, though Joshua uses standard Java terminology. I also agree that over use of Exception in some APIs is a problem. However it is nice to have the choice of different levels of exception seriousness.

nes

Posts: 137
Nickname: nn
Registered: Jul, 2004

Re: Effective Java Exceptions Posted: Jan 18, 2007 8:46 AM
Reply to this message Reply
Excellent analysis. There is something to be said about just crashing forcefully with as much relevant information possible to inform the sysadmin. The most irking aspect of checked exceptions is that you have to handle them right there and then. For errors where the action is log, abort and restart done three levels further up the call stack, having to rethrow an exception is a pain.

This makes me think that it is more critical to correctly architect in languages with explicit typing. When people make every type the lowest and most specific and all exceptions are checked because that produces the fastest and safest code, anybody else having to interface with that code will suffer to no end. With no checked exception there is strictly less power in what you can enforce, on the other hand it reduces the possible amount of damage done by bad architecture decisions.

Jeff Ratcliff

Posts: 242
Nickname: jr1
Registered: Feb, 2006

Re: Effective Java Exceptions Posted: Jan 18, 2007 2:30 PM
Reply to this message Reply
> With no checked exception
> there is strictly less power in what you can enforce, on
> the other hand it reduces the possible amount of damage
> done by bad architecture decisions.

Of course all checked exceptions can really enforce is the addition of a "throws" keyword to a method or an empty catch block. The pain is guaranteed, but enforcing good practice is not.

Morgan Conrad

Posts: 307
Nickname: miata71
Registered: Mar, 2006

Re: Effective Java Exceptions Posted: Jan 21, 2007 11:26 AM
Reply to this message Reply
At this stage in the game, I'd prefer not to change the terminology so much. IMO, "CheckedException" and "UncheckedException" are clearer and match current usage. They should not be subclasses of each other.

Given the debate on another recent thread, I'm tempted to propose that Error be subdivided into JVMError, which programmers should definitely not use (and should be abstract) and ApplicationError, which indicates a serious error in the application.

This is all theoretical, no chance of this changing is there???

Iulian Dragos

Posts: 3
Nickname: jaguarul
Registered: Jan, 2007

Re: Effective Java Exceptions Posted: Jan 22, 2007 8:23 AM
Reply to this message Reply
According to the definition, shouldn't then <code>IOException</code> be a "contingency" exception? I think of the "file not found" case, where the error can very well be expressed without references to internals.

James Watson

Posts: 2024
Nickname: watson
Registered: Sep, 2005

Re: Effective Java Exceptions Posted: Jan 22, 2007 10:35 AM
Reply to this message Reply
> According to the definition, shouldn't then
> <code>IOException</code> be a "contingency" exception? I
> think of the "file not found" case, where the error can
> very well be expressed without references to internals.

Happily there is a FileNotFoundException that can be caught separately from the other IOExceptions.

Whether a given IOException is a fault or a contingency is based largely on the context of the code that is catching it. Is a FileNotFoundException a fault or a contingency? It depends. If the file is required at startup for my application and it has been decided to that no default setup can be assumed, it might be a fault. If the file is being looked up with a user specified String, then it's usually a contingency. In the former case, it's foolish to require that every call to a certain method catch an IOException so you wrap it in a unchecked exception. In the latter, it might make sense to make it part of the throws clause of the method to reinforce that the caller needs to deal with this possibility but some code that calls that API might consider not finding the file to be a fault.

If you are reading this article as 'if exception class A then contingency else fault' prescription, I think you are missing the point. The idea is that as you are developing code you need to be making choices about whether to treat possible exceptions as faults or contingencies. Writers of APIs for general consumption like the JDK have a different view on these questions than end-product developers because they never know how it will be used and whether the caller wants it treated as a fault or a contingency and often lean towards checked exceptions (at least historically.)

Morgan Conrad

Posts: 307
Nickname: miata71
Registered: Mar, 2006

Re: Effective Java Exceptions Posted: Jan 22, 2007 3:56 PM
Reply to this message Reply
>a fault or a contingency? It depends.

I find myself in strong agreement with James. :-)

The problem with Fault and Contingency is that, as he correctly points out, they really depending on circumstances, and end up being very subjective.

Checked / Unchecked, if admittedly less expressive to the overall design, have the big advantage that they are subjective.

Iulian Dragos

Posts: 3
Nickname: jaguarul
Registered: Jan, 2007

Re: Effective Java Exceptions Posted: Jan 23, 2007 1:55 AM
Reply to this message Reply
> Whether a given IOException is a fault or a contingency is
> based largely on the context of the code that is catching
> it.

This sounds reasonable, but the problem is that the library writer doesn't know the context. So he safely bets on checked exceptions. Do you propose an application specific layer which wraps exceptions into checked on unchecked exceptions depending on the application requirements?

> If you are reading this article as 'if exception class A
> then contingency else fault' prescription, I think you are
> missing the point.

I must be missing the point, that's what I'm asking questions :-) So what is the point of this classification? As long as one is writing a library, he never knows the context where his code will be used, therefore whatever choices he makes might be invalidated in some context. I see how (thinking about) these choices makes a lot of sense when developing applications, though.

The idea is that as you are developing
> code you need to be making choices about whether to treat
> possible exceptions as faults or contingencies. Writers
> of APIs for general consumption like the JDK have a
> different view on these questions than end-product
> developers because they never know how it will be used and
> whether the caller wants it treated as a fault or a
> contingency and often lean towards checked exceptions (at
> least historically.)

Fair enough, but the post mentioned something about the designers of the Java APIs doing a 'poor' job. What would be a better design from the point of view of exception handling for Java IO?

James Watson

Posts: 2024
Nickname: watson
Registered: Sep, 2005

Re: Effective Java Exceptions Posted: Jan 23, 2007 6:04 AM
Reply to this message Reply
> > Whether a given IOException is a fault or a contingency
> is
> > based largely on the context of the code that is
> catching
> > it.
>
> This sounds reasonable, but the problem is that the
> library writer doesn't know the context. So he safely bets
> on checked exceptions. Do you propose an application
> specific layer which wraps exceptions into checked on
> unchecked exceptions depending on the application
> requirements?

What I do is if a checked-exception represents a fault in my application, I wrap it in a unchecked-exception. I then have a fault-barrier that does default error handling for unrecoverable problems as described in the article.

> > If you are reading this article as 'if exception class
> A
> > then contingency else fault' prescription, I think you
> are
> > missing the point.
>
> I must be missing the point, that's what I'm asking
> questions :-) So what is the point of this classification?
> As long as one is writing a library, he never knows the
> context where his code will be used, therefore whatever
> choices he makes might be invalidated in some context. I
> see how (thinking about) these choices makes a lot of
> sense when developing applications, though.

I think the issues with checked exceptions were largely improved by the modifications to Throwable that allowed wrapping of exceptions. For library writers, I think there's a general rule of thumb that issues that may be transient should be checked and things that are unlikely to be resolved or problems with the way it's being used are unchecked. But I agree, it's a much tougher thing than when you are writing something and you know how it will be used.

I have taken a slightly different tack in a recent design where I defined an interface that would be called by a robust manager class. I declared most of the methods on the handler interface to throw Exception because my manager has to handle any Exception anyway. In each of the handler implementations, I declare any checked exceptions I need to. I don't really have to wrap anything.

I can see what people mean when they say checked exceptions were a failed experiment but something still tells me that there's some value here. Some refinement is still needed. Since the problems with checked-exceptions obviously understood when Java was born, I think a new language that attempted to build on this idea should make is easier it 'uncheck' exceptions.

I think I've seen you hanging around the Scala mailing list. Why are you interested in this boring Java stuff? : )

> The idea is that as you are developing
> > code you need to be making choices about whether to
> treat
> > possible exceptions as faults or contingencies.
> Writers
> > of APIs for general consumption like the JDK have a
> > different view on these questions than end-product
> > developers because they never know how it will be used
> and
> > whether the caller wants it treated as a fault or a
> > contingency and often lean towards checked exceptions
> (at
> > least historically.)
>
> Fair enough, but the post mentioned something about the
> designers of the Java APIs doing a 'poor' job. What would
> be a better design from the point of view of exception
> handling for Java IO?

I don't know that I agree that the IOException should be unchecked. IO is a pretty general concept and has varying degrees of reliability. Maybe the key is wrapping and not second-guessing the authors of the libraries. I thought I knew some good examples (of bad checked exceptions) but I can't think of any. I was going to say ThreadInterruptedException shouldn't be checked on Thread.sleep() but I guess in a multi-threaded app, this could happen at anytime and shouldn't be considered a fault in that case. Its just that when it's usually used (in my experience), it's in a single-threaded app or one that doesn't interrupt threads.

Iulian Dragos

Posts: 3
Nickname: jaguarul
Registered: Jan, 2007

Re: Effective Java Exceptions Posted: Jan 25, 2007 5:08 AM
Reply to this message Reply
> I think I've seen you hanging around the Scala mailing
> list. Why are you interested in this boring Java stuff? :
> )

That's true. But I can always learn something new even from "boring" Java ;-) In fact, checked exceptions are an interesting issue: normally, I would welcome more static checking, but I find the Java checked exception model not flexible enough. I was curious how other people see it.

> I don't know that I agree that the IOException should be
> unchecked. IO is a pretty general concept and has varying
> degrees of reliability. Maybe the key is wrapping and not
> second-guessing the authors of the libraries. I thought I
> knew some good examples (of bad checked exceptions) but I
> can't think of any. I was going to say
> ThreadInterruptedException shouldn't be checked on
> Thread.sleep() but I guess in a multi-threaded app, this
> could happen at anytime and shouldn't be considered a
> fault in that case. Its just that when it's usually used
> (in my experience), it's in a single-threaded app or one
> that doesn't interrupt threads.

So maybe exception checking should be optional, and classes or methods declare the checking policy they want to enforce. You could then have a "checked" annotation on your Manager class to force compiler errors on missed exceptions, and nothing (default) on the other classes. I think this would be a great example of pluggable types once they make their way into Scala.

Flat View: This topic has 10 replies on 1 page
Topic: Guidelines for Portlet Writers Previous Topic   Next Topic Topic: Martin Fowler on Why Mocks Aren't Stubs

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use