Re: Where shoul I throw RuntimeException
On Fri, 22 May 2009, Giovanni Azua wrote:
"Tom Anderson" <email@example.com> wrote in message
It definitely should not return null - that's almost never a good idea. It
shouldn't throw a RuntimeException, because that won't force the callers
to face up to the possiblity of failure. It could throw another checked
exception, perhaps a domain-specific one like DimkaDataLayerException,
rather an an SQLException. But what is certain - although others, who
labour in ignorance or sin, may disagree - is that it should throw a
checked exception. If there is a real possibility of failure, callers
should be made aware of it, and be made to prepare for it.
I don't think that the first thing one should figure out is what to
throw or rethrow. It is like the first thing that crosses your mind when
you get a client is to point the right "cannons" at him. Just thinking
what is the right cannon caliber "checked" or "unchecked" should not be
the idea behind serving a client. One should rather think hard to serve
the client i.e. require less and ensure more.
That's an admirable sentiment - if a method can recover from an exception,
then yes, it absolutely should (probably - there are times when it would
not be a good idea). My assumption in this thread has been that we're
talking about the times when it can't.
From my experience, the farther the exception gets the less likely any
layer will be able to recover and do anything sensible with it.
To a point - sometimes, the only sensible thing to do is to give up. Log
the exception, report failure to the user, whatever. That's a decision
that can only be made at the top level, and such errors can be escalated
to the top level most easily by throwing an exception.
Everyone has to die sooner or later, whether they be killed by germs,
crushed by a collapsing house, or blown to smithereens by an atom bomb. --