Java中的异常分为两种类型:checked Exception和unchecked Exception。
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.
一个方法没有返回期望值的原因有两个:一个是contingency(应变),一个是fault(故障)。
一个contingency应该被程序设计者考虑到,并把它作为程序的正常行为之一,它对影到checked exception对于一个方法而言,它应该把contingency的情况大包为checked exception抛出;如果是库类的方法,一定要设计好,因为方法总会有些不太常出现,但是还是会可能的返回情况,这就刚好用checked exception来表达,当应用程序调用该方法的时候,会根据不同的情况对其进行分别处理,从而返回给最终使用者一个正确的值。抛出这种异常,应该完全不影响程序的正常运行
一个fault是设计者认为不会发生的,它对应到unchecked exception。
条件 | 应变 | 故障 |
被认为是 | 设计的一部分 | 一个糟糕的意外 |
预计会发生 | 经常发生 | 不会发生 |
关注方 | 上游调用 | 需要修好找个问题的人 |
价值 | 另外一种返回方式 | 程序bug,硬件系统故障,配置错误,丢失的文件,服务器没有运行 |
与异常匹配 | checked | unchecked |
参考资料:
Effective Java Exceptions
http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html