directory-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Niclas Hedhman <nic...@hedhman.org>
Subject Re: Constructors & Exceptions
Date Fri, 04 Jan 2008 03:49:08 GMT
On Friday 04 January 2008 06:15, Felix Knecht wrote:
> Client's reaction when exception happens | Exception type
> -----------------------------------------+-------------------------------
> Client code cannot do anything           | Make it an unchecked exception
>                                          +
> Client code will take some useful        | Make it a checked exception
> recovery action based on information in  |
> exception

On paper this sounds fine. But I kind of disagree. If a unchecked exception 
bubbles through the system to some high-up catcher which logs it, and then 
acts, you often end up with a context-less information about the problem, and 
you need to dig into the stack trace.

Instead, I typically recommend;

Is this the result of a bug in the code?  -->  Unchecked.
Can this happen with no bugs in the code? -->  Checked.

Now, that is often a contract between the caller and callee. The callee can 
perhaps not know whether this could be the result from a bug or a 'normal 
case'. *I* then use checked exception in the low-level method, and add a 
wrapper at the caller end, which is used when the arguments (for instance) 
are guaranteed to be Ok. For example; the constructor of URL throws 
MalformedURLException, and when you do

 URL url = new URL( "http://www.apache.org" );

it is really annoying that you need to catch it. So, you add your newHttpUrl() 
in a factory, which you call instead for the above kind of cases.

By having checked exceptions for things that can happen in normal situations 
(disk full, no connection, wrong data input, et cetera) is to ensure that 
each level in the call chain wraps a user relevant context and re-throw the 
exception, typically as a different type. So, the user is presented with a 
caller chain like ; 
"Build Error" -> 
"Artifact org.apache.directory:core:1.1.0 missing" -> 
"Can't download artifact org.apache.directory:core:1.1.0" -> 
"No route to host: www.ibiblio.org" ->
"Connection error."

without needing to dig into stacktraces, and often not know the context enough 
to have a clue what went wrong.

IMHO, exception handling is a very sad chapter in most software.


Cheers
-- 
Niclas Hedhman, Software Developer

I  live here; http://tinyurl.com/2qq9er
I  work here; http://tinyurl.com/2ymelc
I relax here; http://tinyurl.com/2cgsug

Mime
View raw message