Re: Why does Java require the throws clause? Good or bad language
design?
James Harris wrote:
I haven't caught up with all the posts yet so this may have been
discussed but to come back to my original point - and my original and
only complaint - about Java's syntax: if I have a /chain/ of methods,
want to detect errors in the lowest and handle them in the highest
doesn't this mean there is a greater 'overhead' in method signatures
than your post suggests? Doesn't each and every intervening method
need the same throws clause?
If the lower methods declare they will throw just five checked
exceptions don't these all need declaring in every intervening method?
If there are ten intervening methods isn't that 50 exceptions to add?
The situation is, in fact, worse than this suggests as each method may
well call more than one other method, each of which throws its own
errors.
In other words my challenge on Java is that checked exceptions don't
seem to scale well. I understand this issue can be "fixed" by various
means but these are not natural parts of the language.
That would not be the usual handling of exceptions, but anyway it isn't 50
exceptions, it's five exceptions on ten methods.
This is similar to the overhead of declaring the parameters for each of the
ten methods.
If you wrote a chain of methods that rethrow checked exceptions all the way
up, that was a design decision and presumably there was a good reason for it.
Other idioms exists, however, so this choice is not mandatory. The "fixes"
are, indeed, a "natural part" of Java, since the natural idioms in Java are:
- Catch and handle the exception - no rethrow.
- Catch and rethrow, or simply pass through a checked exception - the scenario
you did not like but is really just fine.
- Catch a checked exception and wrap in an unchecked one, then throw the
unchecked exception - no throws clause needed above this.
- Catch the five exceptions at the lowest level, log them, then wrap in a
single, application-specific checked exception that all higher methods recognize.
This last is probably the most common. Once you've handled the exception at
the lowest level, you really don't care any more whether it was a
ServletException or an IOException; at that point it is just a MyAppException
with the original Throwable as its cause.
All these are quite "natural" and most of them reduce the overhead of the
throws clause.
Personally, I think all this fuss over a little extra typing for the throws
clause is a combination of laziness and not understanding the exception idioms.
- Lew