正如其他答案所指出的那样,throws子句只需要
checked exceptions,这是目前只存在于Java中的一个功能.
关于Java为什么检查异常的官方答案是well documented:
Why did the designers decide to force
a method to specify all uncaught
checked exceptions that can be thrown
within its scope? Any Exception that
can be thrown by a method is part of
the method’s public programming
interface. Those who call a method
must know about the exceptions that a
method can throw so that they can
decide what to do about them. These
exceptions are as much a part of that
method’s programming interface as its
parameters and return value.
但是,即使在Java社区内,这个决定也是highly controversial:
Recently, several well-regarded
experts, including Bruce Eckel and Rod
Johnson, have publicly stated that
while they initially agreed completely
with the orthodox position on checked
exceptions, they’ve concluded that
exclusive use of checked exceptions is
not as good an idea as it appeared at
first, and that checked exceptions
have become a significant source of
problems for many large projects.
Eckel takes a more extreme view,
suggesting that all exceptions should
be unchecked; Johnson’s view is more
conservative, but still suggests that
the orthodox preference for checked
exceptions is excessive. (It’s worth
noting that the architects of C#, who
almost certainly had plenty of
experience using Java technology,
chose to omit checked exceptions from
the language design, making all
exceptions unchecked exceptions. They
did, however, leave room for an
implementation of checked exceptions
at a later time.)
就个人而言,我发现只有当你的API养成捕获所有异常的习惯并将它们作为适合你的抽象层的东西重新抛出时,才会发现检查异常是有用的.例如,碰巧使用磁盘或SQL后端来缓存数据的内存中对象缓存应该永远不会抛出IOException或SQLException – 相反,它应该抛出(并声明)一些用户定义的异常,如CacheFailureException或类似的异常.
此外,你可能会发现Ned Batchelder的文章Exceptions in the Rainforest对这个问题很有启发性.