Tuesday, 17 November 2009

Java: how to use an IllegalArgumentException

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 IllegalArgumentException (the exception type).

What is it telling you?

If your application throws an IllegalArgumentException, you've screwed up. As the documentation says:

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

Some code:

public class MyBadCode {
  public static void main(String[] args) {
    Percentage percentage = new Percentage(121);

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 Percentage 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).

An 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.

This Percentage type only accepts values between 0 and 100 inclusive; any value outside that range throws an exception.

public final class Percentage {
  private final int value;

   * A percentage value must be between 0 and 100 inclusive.
   @param value
   *          the percentage value
  public Percentage(int value) {
    if (value < || value > 100) {
      throw new IllegalArgumentException(Integer.toString(value));
    this.value = value;

  public int getValue() {
    return value;

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.

Throw IllegalArgumentException if your method or constructor doesn't accept a null value. NullPointerException indicates that your code tried to use a null value. You never need to throw a NullPointerException yourself.

No comments:

Post a Comment

All comments are moderated