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 }
An exception should be thrown when a function experiences a failure, i.e., an error. A function is a unit of work, and failures should be viewed as errors or otherwise based on their impact on functions.
Yes, throw the exception in the setter. If your code throws IllegalArgumentException at some later point in time, it would be confusing to the caller. From the docs: Thrown to indicate that a method has been passed an illegal or inappropriate argument.
To specify that writeList can throw two exceptions, add a throws clause to the method declaration for the writeList method. The throws clause comprises the throws keyword followed by a comma-separated list of all the exceptions thrown by that method.
The throw keyword in Java is used for explicitly throwing a single exception. This can be from within a method or any block of code. Both checked and unchecked exceptions can be thrown using the throw keyword.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With