如果我有一个要修改某些值的 set 方法, 如果用户输入了错误的值,哪个是指示失败的最佳抛出异常?
public void setSomething(int d) throws ....
{
if (d < 10 && d >= 0)
{
// ok do something
}
else throw new ... // throw some exception
}
最佳答案
我会选择 IllegalArgumentException .
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
编辑
另一个说明:
代替
if (conditionIsTrue) {
doThis();
doThat();
} else {
throw new IllegalArgumentException();
}
写:
if (conditionNotTrue) {
throw new IllegalArgumentException();
}
doThis();
doThat();
(虽然这个建议可能会引起争议 ;-))。
关于java - 在 set 方法中抛出的最佳异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7334192/