Java - IllegalArgumentException



The Java IllegalArgumentException is thrown when an illegal or inappropriate argument is passed to a method. The IllegalArgumentException is a runtime exception that is thrown when a method is passed an illegal or inappropriate argument.

Following is the reason when JVM throws an IllegalArgumentException in Java:

  • When the user passes an illegal or inappropriate argument to a method, JVM throws an IllegalArgumentException.

Constructors of IllegalArgumentException

There are two constructors of IllegalArgumentException class:

  • IllegalArgumentException(): This constructor is used to create an IllegalArgumentException object without any message.
  • IllegalArgumentException(String message): This constructor is used to create an IllegalArgumentException object with a message.

Methods of IllegalArgumentException

There are some methods of IllegalArgumentException class:

Method Description
getMessage() It is used to return the message of the exception.
toString() It is used to return the detail message string of the exception.
printStackTrace() It is used to print the stack trace of the exception.

Example of IllegalArgumentException

In this example, we are passing an illegal argument to the method, so JVM will throw an IllegalArgumentException.

public class IllegalArgumentExceptionExample {

   public static void main(String[] args) {
      int num = -1;
      if(num < 0) {
         throw new IllegalArgumentException("Number can't be negative");
      }
   }
}

Output

Following is the output of the above code:

Exception in thread "main" java.lang.IllegalArgumentException: Number can't be negative
    at IllegalArgumentExceptionExample.main(IllegalArgumentExceptionExample.java:6)

As you can see in the output, JVM throws an IllegalArgumentException because we are passing an illegal argument to the method.

Handling IllegalArgumentException

In this example, we are passing an illegal argument to the method, so JVM will throw an IllegalArgumentException. We are handling this exception using try-catch block.

public class IllegalArgumentExceptionExample {

   public static void main(String[] args) {
      int num = -1;
      try {
         if(num < 0) {
            throw new IllegalArgumentException("Number can't be negative");
         }
      } catch(IllegalArgumentException e) {
         System.out.println("Illegal argument passed to the method");
      }
   }
}

Output

Following is the output of the above code:

Illegal argument passed to the method

How to avoid IllegalArgumentException?

There are some ways to avoid IllegalArgumentException in Java:

  • Always check the argument before passing it to the method.
  • Always validate the argument before passing it to the method.
  • Always use the if-else statement to check the argument before passing it to the method.

By following the above ways, you can avoid IllegalArgumentException in Java.

java_lang_exceptions.htm
Advertisements