|
| Chris Smith wrote:
> I think we're largely in agreement, but I'll nitpick anyway. Hope you
> don't mind! :)
I don't mind at all.
Lew <lew@nospam.lewscanon.com> wrote:
[color=darkred]
> Clearly the throws statement is not needed in any case. The point that
> it can be inferred is a valid one. The further point that it can be
> inferred incorrectly is also important; but as a default, most (I'd
> guess 99%) methods want to declare only the exceptions that they
> actually throw.
Meaningless statistic, and begs the question of what the throws clause is for.
The throws clause allows programs that use, say, interfaces and abstract
classes to invoke behavior to know what possible exceptions must be checked.
There is no way for such a class to know at compile time which runtime method
might actually be invoked, and it can vary from run to run of the same
program. The throws clause does not exist to support cases where the inference
can be made, it exists to lock down a guarantee that allows the compiler to
perform validation of a method's contract. Thus I can compile a JAR with
complete assurance of the contract, enforced at compile time, that all client
classes outside the JAR will know what exceptions to catch.
The throws clause is a design artifact, something the API programmer uses to
force compliance to a contract, and whether there is at contract definition
time even an implementation, let alone some arbitrary percentage that uses all
the declared exceptions, is irrelevant. What is relevant is that all future
implementations will adhere to the same contract, so that client software will
not have to reinfer the throws clause just because I changed an implementation
detail in revision 2.
I might call it reasonable that the default is to infer
> the clause and let it be explicitly specified if desired. I might also
> want a warning, though, whenever a public or protected method in a
> public class fails to explicitly specify a throws clause.
There is absolutely nothing wrong with failing to specify a throws clause in
Java. That is part of the design of the method. The programmer's job is to
design the method to fulfill the contract, so don't throw any checked
exceptions that the contract does not specify, but throw all the unchecked
exceptions that you like, or none, as you like.
The throws clause is OPTIONAL. People are arguing about it like it is some
sort of stricture - you DO NOT NEED TO DECLARE A THROWS CLAUSE IN ANY METHOD
if you do not want to force calling code to deal with such an exception. If
you have an issue with a method someone else wrote that used the throws
clause, your beef is with the API designer, not the language.
- Lew
|
|