Blog |

How to Throw IllegalArgumentException in Java

How to Throw Illegal<wbr>Argument<wbr>Exception in Java
Table of Contents

The IllegalArgumentException is an unchecked exception in Java that is thrown to indicate an illegal or unsuitable argument passed to a method. It is one of the most common exceptions in Java.

To illustrate, it's like what happens when trying to set a password in a registration system with specific requirements. If the system expects an 8 character password with at least one number and one special character and you enter "password" or "password123", the system rejects it and notifies you of the invalid input. Similarly, Java methods throw the IllegalArgumentException to reject inappropriate or incorrect arguments, ensuring the input meets the required criteria.

What Causes IllegalArgumentException

An IllegalArgumentException is thrown when an argument passed to a method doesn't fit within the logic of the usage of the argument. Some of the most common scenarios for this are:

  • If the argument is out of range. For example, if a method declares an integer age as a parameter, which is expected to be a positive integer. If a negative integer value is passed, an IllegalArgumentException is thrown.
  • If the format of the argument is invalid. For example, if a method declares a string email as a parameter, which is expected in an email address format but a regular string is passed that doesn’t match the format.
  • If the argument is null. In such cases, the IllegalArgumentException is thrown when the method expects a non-empty object as an argument.

IllegalArgumentException Example

Here is an example of an IllegalArgumentException thrown when the argument passed to a method is out of range:

public class Person {
    int age;

    public void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age must be greater than zero"); //Throw IllegalArgumentException if age is negative
        } else {
            this.age = age;
            System.out.println("The person's age is: " + this.age);
        }
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.setAge(-1);
    }
}

In this example, the main() method calls the setAge() method with the age argument set to -1. Since setAge() expects age to be a positive number, it throws an IllegalArgumentException:

Exception in thread "main" java.lang.IllegalArgumentException: Age must be greater than zero
    at Person.setAge(Person.java:6)
    at Person.main(Person.java:14)

How to Resolve IllegalArgumentException

Try following these steps to resolve an IllegalArgumentException in Java:

  1. Inspect the exception stack trace. Carefully analyze the stack trace and identify the method that passes the illegal argument.
  2. Update the code and ensure the passed argument is valid. Make sure that the passed argument is legal and appropriate within the method that uses it.
  3. Catch and handle the exception. To catch the IllegalArgumentException, try-catch blocks can be used. Certain situations can be handled using a try-catch block such as asking for user input again instead of stopping execution when an illegal argument is encountered.

The earlier example can be updated to ensure the passed argument is valid and within the range expected by the method:

public class Person {
    int age;

    public void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age must be greater than zero");
        } else {
            this.age = age;
            System.out.println("The person's age is: " + this.age);
        }
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.setAge(10); //Passing positive value to avoid exception
    }
}

Here, the argument passed to the setAge() method is a positive number, which is what the method expects. Since this argument is valid and within the range expected by the method, the IllegalArgumentException is avoided and the code runs successfully, producing the correct output as expected:

The person's age is: 10

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Try it today!

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape