Calling my web log Illegal Argument Exception seemed like a clever idea at the time. It is probably just a recipe for confusing Java neophytes searching for their program errors. I should've listened to what my granny used to tell me about clarity, precision, and terseness when choosing identifiers.
To make up for it, here's a short post about
(the exception type).
What is it telling you?
If your application throws an
you've screwed up. As the documentation
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
The above code throws an exception:
Exception in thread "main" java.lang.IllegalArgumentException: 121 at Percentage.
(Percentage.java:12) at MyBadCode.main(MyBadCode.java:3)
Reading the stack trace, I can see that the error is on line 3. I
should have read the documentation about how to use the
type (which I just made up for this example; see below).
When should you catch it?
Never (or as close to never as makes no difference).
IllegalArgumentException generally indicates a
bug in your application. The remedy is to fix the bug.
How should you use it in your own code?
Throw it if the arguments passed to your method fall outside acceptable values.
Percentage type only accepts values between
100 inclusive; any value outside that range throws an
Code should fail as early as possible; validate inputs on setter methods and constructors. This helps identify the erroneous code that tried to set the illegal value.
IllegalArgumentException if your method or
constructor doesn't accept a
indicates that your code tried to use a
value. You never need to throw a