Re: Where shoul I throw RuntimeException
I V wrote:
I'm kind of theoretically skeptical about Java's checked exceptions,
although the problem isn't the checking, but having to specify them,
which forces code that otherwise doesn't need to know about exceptions to
deal with them.
That makes exactly as much sense as complaining that 'Baz foo( Bar
arg )' forces client code to use an argument of type 'Bar' and to deal
with a return type of 'Baz' when it otherwise wouldn't have to deal
with them.
The whole *point* of checked exceptions is to force client code to
deal with them.
The fact that exceptions propagate through layers until
they reach the appropriate level at which to handle them is one of their
advantages; forcing the author to specify exceptions at every level gets
in the way of that, cluttering the intermediate layers. The compiler
But that is the point of checked exceptions. If the API writer didn't
want the client to deal with them, he'd have used a runtime exception.
Checked exceptions exist for the very purpose of making client code
deal with them. Complaining that they do what they're designed to do
is very strange.
knows (or, could work out) what exceptions a method could throw, and it
could check they get handled without requiring they are specified
explicitly.
That is a simplistic suggestion. The compiler cannot know what
subtypes' overrides might throw, and this suggestion wouldn't let the
API writer control exceptions as part of the method signature.
Remember that one of the design principles of Java is to support
strong typing and the concomitant type safety. Checked exceptions are
representative of that philosophy.
Having said that, I haven't actually found specifying exceptions to be as
much as a problem as I would have imagined. I'm coming round to the view
that the distinction between checked and unchecked exceptions reflects a
pretty real distinction between those exceptions that should be handled
close to where they occur, and those that don't.
This is a false dichotomy.
The difference isn't where they're handled but whether the client code
should be forced to handle them. The rule of thumb is that runtime
exceptions require a code change in the client to eliminate them,
checked exceptions do not.
--
Lew