我写了以下方法:
public int count(int x){
//method contents
}
参数 x 必须介于 0 和 10 之间,尽管使用此代码的任何人都不会遇到问题,因为使用此方法的任何人都不会遇到不满足要求的 x。由于调用“count”方法的次数较多,捕获和处理检查的异常可能会有点乏味。强制 x 始终在 0 到 10 之间的最佳方法是什么:检查异常、非检查异常还是断言?
最佳答案
- 检查异常绝对是不可能的,因为它们只对可能发生的事件有意义,与输入的有效性无关1;
- 未经检查的异常作为验证错误是有意义的:例如,按照书本规定抛出
IllegalArgumentException
; - Java 断言只能用于断言方法的不变量,即必须保存任何输入的方法。断言失败应该意味着“有罪的部分”不是调用者,而是方法的代码本身。
1 Josh Bloch,《高效 Java》,第 41 条:
The burden [of checked exceptions] is justified if the exceptional condition cannot be prevented by proper use of the API and the programmer using the API can take some useful action once confronted with the exception. Unless both of these conditions hold, an unchecked exception is more appropriate.
关于Java:何时使用检查异常、非检查异常或断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25126869/