Re: Why does Java require the throws clause? Good or bad language
design?
Robbert Haarman wrote:
Of course, I wasn't claiming that the information comes from nowhere. Of
course, it comes from something some programmer entered. All I meant is
that it can be deduced from throw statements, and that the throws clause
is, thus, redundant.
No, it can't, because not every implementation of a method will necessarily
throw every checked exception for that method. The only way for Java to know
what checked exceptions might (not will) be thrown is through the throws
clause, and the throws clause is, thus, not redundant.
There is no general way for Javadocs to infer what may be thrown save by at
least the throws clause, and in practice, by the @throws tag. Thus the idea
that Javadocs might figure into the "automagic" throws mechanism is not, at
present, real.
There is no general way, in the face of interfaces, abstract classes, and
method overrides in extrinsic subclasses linked at runtime, to magically
deduce at compile time what checked Exceptions might be thrown. That isn't
what checked exceptions are for in the first place. They exist for an API
designer to specify what checked Exceptions are allowed to be thrown, and
therefore must be checked. The throws clause does not guarantee which ones of
those will be thrown. So you cannot analyze from what is thrown at runtime
what the API designer intended should be allowed. Ergo, the throws clause
exists to give the API designer that power.
This must be a manual entry by the programmer, up until we get computers that
do what we want instead of what we tell them.
- Lew