开发者

Best exception to throw inside a set method

If I have a set method in which I want to modify some values, if an user enter wrong values which is the best exception to throw to indicate that failure?

public void setSomething(int d) throws ....
{
    if (d < 10 && d >= 0)
    {
        // ok do something
    }
    else throw new ...开发者_开发知识库 // throw some exception
}


I'd go for IllegalArgumentException.

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

EDIT

Another note:

Instead of

if (conditionIsTrue) {
  doThis();
  doThat();
} else { 
  throw new IllegalArgumentException();
}

write:

if (conditionNotTrue) {
    throw new IllegalArgumentException();
}

doThis();
doThat();

(Though this advice may be controversial ;-)).


I agree with @Code Monkey about creating your own InvalidArgumentException, but his implementation doesn't show all the advantages it provides.

1) You can add convenience methods to simplify argument checking. For example:

InvalidArgumentException.throwIfNullOrBlank(someString, "someString");

vs.

if (someString == null || someString.trim().isEmpty()) {
    throw new IllegalArgumentException("someString is null or blank");
}

2) You can write unit tests that confirm which argument was invalid. If you throw IllegalArgumentException, your unit test can't confirm that it was thrown for the reason you expect it to be thrown. You can't even tell that it was thrown by your own code.

try {
    someClass.someMethod(someValue);
    Assert.fail("Should have thrown an InvalidArgumentException");
} catch (InvalidArgumentException e) {
    Assert.assertEquals("someValue", e.getArgumentName());
}

3) You can tell that the exception was thrown from within your own code. (This is a minor point that doesn't have much practical advantage)


If the number is an index, you could use IndexOutOfBoundsException. Otherwise, as Oliver says, IllegalArgumentException.

Don't be afraid to create a subclass of IllegalArgumentException to be more precise about the problem. Any catch blocks written for IllegalArgumentException will still catch it, but the stack trace will be slightly more informative.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜