java.lang.IllegalArgumentException – Reasons and How to Solve?

Here you will learn possible causes of Exception in thread “main” java.lang.IllegalArgumentException and ways to solve it.

I hope you know the difference between error and exception. Error means programming mistake that can be recoverable only by fixing the application code. But exceptions will arise only when exceptional situations occurred like invalid inputs, null values, etc. They can be handled using try catch blocks.

java.lang.IllegalArgumentException will raise when invalid inputs passed to the method. This is most frequent exception in java.

Reasons for java.lang.IllegalArgumentException

Here I am listing out some reasons for raising the illegal argument exception

  • When Arguments out of range. For example percentage should lie between 1 to 100. If user entered 200 then illegalarugmentexcpetion will be thrown.
  • When arguments format is invalid. For example if our method requires date format like YYYY/MM/DD but if user is passing YYYY-MM-DD. Then our method can’t understand. Then illegalargument exception will raise.
  • When closed files has given as argument for a method to read that file. That means argument is invalid.
  • When a method needs non empty string as a parameter but null string is passed.

Like this when invalid arguments given then it will raise illegal argument exception.

How to Handle java.lang.IllegalArgumentException?

IllegalArgumentException extends RuntimeException and it is unchecked exception. So we don’t need to catch it. We have to fix the code to avoid this exception.

Hierachy of illegalArgumentException:

  • java.lang.Object
    • java.lang.Throwable
      • java.lang.Exception
        • java.lang.RuntimeException
          • java.lang.illegalArgumentException

Example program which will raise illegalArgumentException.

public class Student
{
	int m;

	public void setMarks(int marks)
	{
		if(marks<0 || marks>100)  //here we are validating the inputs
			throw new IllegalArgumentException(Integer.toString(marks));  //we are creating the object of IllegalArgumentException class
		else
			m=marks;
	}

	public static void main(String[] args)
	{
		Student obj= new Student();   //creating first object
		obj.setMarks(45);             // assigning valid input 
		System.out.println(obj.m);    // here value will be printed because it is valid
		
		Student obj2=new Student();     // creating second object
		obj2.setMarks(150);             // assigning invalid input, it will throw illegalArgumentException
		System.out.println(obj2.m);    // this statement will not be executed.
	}
}

Output

Exception in thread "main" 45
java.lang.IllegalArgumentException: 150
	at Student.setMarks(Student.java:8)
	at Student.main(Student.java:20)

The main use of this IllegalArgumentException is for validating the inputs coming from other sites or users.

If we want to catch the IllegalArgumentException then we can use try catch blocks. By doing like this we can handle some situations. Suppose in catch block if we put code to give another chance to the user to input again instead of stopping the execution especially in case of looping.

Example Program:

import java.util.Scanner;

public class Student {
	public static void main(String[] args) {
		String cont = "y";
		run(cont);
	}
	
	static void run(String cont) {
		Scanner scan = new Scanner(System.in);
		
		while(cont.equalsIgnoreCase("y")) {
			try {
				System.out.println("Enter an integer: ");
				int marks = scan.nextInt();
				
				if (marks < 0 || marks>100)	//here we are validating input 
					throw new IllegalArgumentException("value must be non-negative and below 100");	//if invalid input then it will throw the illegalArgumentException
				
				System.out.println( marks);
			}
			catch(IllegalArgumentException i) {	// when  out of range is encountered catch block will catch the exception.
			System.out.println("out of range encouneterd. Want to continue");
			cont = scan.next();	// here it is asking whether to continue if we enter y it will again run instead of stopping
		
			if(cont.equalsIgnoreCase("Y"))
				run(cont);
			}
		}
	}
}

Output

Enter integer1
1
Enter integer100
100
Enter integer150
Outofrange encountered want to continue
Y
Enter integer 1

Comment below if you have queries or found any mistake in above tutorial for java.lang.IllegalArgumentException.

Leave a Comment

Your email address will not be published. Required fields are marked *