Java lang illegalargumentexception что за ошибка как исправить

An unexpected event occurring during the program execution is called an Exception. This can be caused due to several factors like invalid user input, network failure, memory limitations, trying to open a file that does not exist, etc. 

If an exception occurs, an Exception object is generated, containing the Exception’s whereabouts, name, and type. This must be handled by the program. If not handled, it gets past to the default Exception handler, resulting in an abnormal termination of the program.

IllegalArgumentException 

The IllegalArgumentException is a subclass of java.lang.RuntimeException. RuntimeException, as the name suggests, occurs when the program is running. Hence, it is not checked at compile-time.

IllegalArgumentException Cause

When a method is passed illegal or unsuitable arguments, an IllegalArgumentException is thrown.

The program below has a separate thread that takes a pause and then tries to print a sentence. This pause is achieved using the sleep method that accepts the pause time in milliseconds. Java clearly defines that this time must be non-negative. Let us see the result of passing in a negative value.

Program to Demonstrate IllegalArgumentException:

Java

public class Main {

    public static void main(String[] args)

    {

        Thread t1 = new Thread(new Runnable() {

            public void run()

            {

                try {

                    Thread.sleep(-10);

                }

                catch (InterruptedException e) {

                    e.printStackTrace();

                }

                System.out.println(

                    "Welcome To GeeksforGeeks!");

            }

        });

        t1.setName("Test Thread");

        t1.start();

    }

}

Output:

Exception in thread "Test Thread" java.lang.IllegalArgumentException: 
timeout value is negative
    at java.base/java.lang.Thread.sleep(Native Method)
    at Main$1.run(Main.java:19)
    at java.base/java.lang.Thread.run(Thread.java:834)

In the above case, the Exception was not caught. Hence, the program terminated abruptly and the Stack Trace that was generated got printed.

Diagnostics & Solution

The Stack Trace is the ultimate resource for investigating the root cause of Exception issues. The above Stack Trace can be broken down as follows.

Part 1: This part names the Thread in which the Exception occurred. In our case, the Exception occurred in the “Test Thread”.

Part 2: This part names class of the Exception. An Exception object of the “java.lang.IllegalArgumentException” class is made in the above example.

Part 3: This part states the reason behind the occurrence of the Exception. In the above example, the Exception occurred because an illegal negative timeout value was used.

Part 4: This part lists all the method invocations leading up to the Exception occurrence, beginning with the method where the Exception first occurred. In the above example, the Exception first occurred at Thread.sleep() method. 

From the above analysis, we reach the conclusion that an IllegalArgumentException occurred at the Thread.sleep() method because it was passed a negative timeout value. This information is sufficient for resolving the issue. Let us accordingly make changes in the above code and pass a positive timeout value.

Below is the implementation of the problem statement:

Java

public class Main {

    public static void main(String[] args)

    {

        Thread t1 = new Thread(new Runnable() {

            public void run()

            {

                try {

                    Thread.sleep(10);

                }

                catch (InterruptedException e) {

                    e.printStackTrace();

                }

                System.out.println(

                    "Welcome To GeeksforGeeks!");

            }

        });

        t1.setName("Test Thread");

        t1.start();

    }

}

Output

Welcome To GeeksforGeeks!

Last Updated :
02 Feb, 2021

Like Article

Save Article

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 that occur in Java.

Since IllegalArgumentException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor.

What Causes IllegalArgumentException

An IllegalArgumentExceptioncode> occurs 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:

  1. When the arguments passed to a method are 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 will be thrown.
  2. When the format of an argument is invalid. For example, if a method declares a string email as a parameter, which is expected in an email address format.
  3. If a null object is passed to a method when it expects a non-empty object as an argument.

IllegalArgumentException Example

Here is an example of a 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");
        } else {
            this.age = 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 agecode> argument set to -1. Since setAge()code> expects age to be a positive number, it throws an IllegalArgumentExceptioncode>:

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

The following steps should be followed to resolve an IllegalArgumentException in Java:

  1. Inspect the exception stack trace and identify the method that passes the illegal argument.
  2. Update the code to make sure that the passed argument is valid within the method that uses it.
  3. 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.

Track, Analyze and Manage Java Errors With Rollbar

![Rollbar in action](https://rollbar.com/wp-content/uploads/2022/04/section-1-real-time-errors@2x-1-300×202.png)

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 Java error monitoring and triaging, making fixing errors easier than ever. Try it today.

A quick guide to how to fix IllegalArgumentException in java and java 8?

1. Overview

In this tutorial, We’ll learn when IllegalArgumentException is thrown and how to solve IllegalArgumentException in java 8 programming.

This is a very common exception thrown by the java runtime for any invalid inputs. IllegalArgumentException is part of java.lang package and this is an unchecked exception.

IllegalArgumentException is extensively used in java api development and used by many classes even in java 8 stream api.

First, we will see when we get IllegalArgumentException in java with examples and next will understand how to troubleshoot and solve this problem?

Java - How to Solve IllegalArgumentException?

2. Java.lang.IllegalArgumentException Simulation

In the below example, first crated the ArrayList instance and added few string values to it. 

package com.javaprogramto.exception.IllegalArgumentException;

import java.util.ArrayList;
import java.util.List;

public class IllegalArgumentExceptionExample {

	public static void main(String[] args) {
		
		// Example 1
		List<String> list = new ArrayList<>(-10);
		list.add("a");
		list.add("b");
		list.add("c");
	}
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Illegal Capacity: -10
	at java.base/java.util.ArrayList.<init>(ArrayList.java:160)
	at com.javaprogramto.exception.IllegalArgumentException.IllegalArgumentExceptionExample.main(IllegalArgumentExceptionExample.java:11)

From the above output, we could see the illegal argument exception while creating the ArrayList instance.

Few other java api including java 8 stream api and custom exceptions.

3. Java IllegalArgumentException Simulation using Java 8 stream api

Java 8 stream api has the skip() method which is used to skip the first n objects of the stream.

public class IllegalArgumentExceptionExample2 {

	public static void main(String[] args) {
		
		// Example 2
		List<String> stringsList = new ArrayList<>();
		stringsList.add("a");
		stringsList.add("b");
		stringsList.add("c");
		
		stringsList.stream().skip(-100);
	}
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: -100
	at java.base/java.util.stream.ReferencePipeline.skip(ReferencePipeline.java:476)
	at com.javaprogramto.exception.IllegalArgumentException.IllegalArgumentExceptionExample2.main(IllegalArgumentExceptionExample2.java:16)

4. Java IllegalArgumentException – throwing from custom condition

In the below code, we are checking the employee age that should be in between 18 and 65. The remaining age groups are not allowed for any job.

Now, if we get the employee object below 18 or above 65 then we need to reject the employee request.

So, we will use the illegal argument exception to throw the error.

import com.javaprogramto.java8.compare.Employee;

public class IllegalArgumentExceptionExample3 {

	public static void main(String[] args) {

		// Example 3
		Employee employeeRequest = new Employee(222, "Ram", 17);

		if (employeeRequest.getAge() < 18 || employeeRequest.getAge() > 65) {
			throw new IllegalArgumentException("Invalid age for the emp req");
		}

	}
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Invalid age for the emp req
	at com.javaprogramto.exception.IllegalArgumentException.IllegalArgumentExceptionExample3.main(IllegalArgumentExceptionExample3.java:13)

5. Solving IllegalArgumentException in Java

After seeing the few examples on IllegalArgumentException, you might have got an understanding on when it is thrown by the API or custom conditions based.

IllegalArgumentException is thrown only if any one or more method arguments are not in its range. That means values are not passed correctly.

If IllegalArgumentException is thrown by the java api methods then to solve, you need to look at the error stack trace for the exact location of the file and line number.

To solve IllegalArgumentException, we need to correct method values passed to it. But, in some cases it is completely valid to throw this exception by the programmers for the specific conditions. In this case, we use it as validations with the proper error message.

Below code is the solution for all java api methods. But for the condition based, you can wrap it inside try/catch block. But this is not recommended.

package com.javaprogramto.exception.IllegalArgumentException;

import java.util.ArrayList;
import java.util.List;

import com.javaprogramto.java8.compare.Employee;

public class IllegalArgumentExceptionExample4 {

	public static void main(String[] args) {

		// Example 1
		List<String> list = new ArrayList<>(10);
		list.add("a");
		list.add("b");
		list.add("c");

		// Example 2
		List<String> stringsList = new ArrayList<>();
		stringsList.add("a");
		stringsList.add("b");
		stringsList.add("c");

		stringsList.stream().skip(2);

		// Example 3
		Employee employeeRequest = new Employee(222, "Ram", 20);

		if (employeeRequest.getAge() < 18 || employeeRequest.getAge() > 65) {
			throw new IllegalArgumentException("Invalid age for the emp req");
		}
		
		System.out.println("No errors");

	}
}

Output:

6. Conclusion

In this article, We’ve seen how to solve IllegalArgumentException in java.

GitHub

IllegalArgumentException

In this tutorial, we will discuss how to solve the java.lang.illegalargumentexception – IllegalArgumentException in Java.

This exception is thrown in order to indicate that a method has been passed an illegal or inappropriate argument. For example, if a method requires a non-empty string as a parameter and the input string equals null, the IllegalArgumentException is thrown to indicate that the input parameter cannot be null.

You can also check this tutorial in the following video:

java.lang.IllegalArgumentException – Video

This exception extends the RuntimeException class and thus belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause. Finally, the IllegalArgumentException exists since the first version of Java (1.0).

java.lang.IllegalArgumentException

The IllegalArgumentException is a good way of handling possible errors in your application’s code. This exception indicates that a method is called with incorrect input arguments. Then, the only thing you must do is correct the values of the input parameters. In order to achieve that, follow the call stack found in the stack trace and check which method produced the invalid argument.

The following example indicates a sample usage of the java.lang.IllegalArgumentException – IllegalArgumentException.

IllegalArgumentExceptionExample.java

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

import java.io.File;

public class IllegalArgumentExceptionExample {

    /**

     *

     * @param parent, The path of the parent node.

     * @param filename, The filename of the current node.

     * @return The relative path to the current node, starting from the parent node.

     */

    public static String createRelativePath(String parent, String filename) {

        if(parent == null)

            throw new IllegalArgumentException("The parent path cannot be null!");

        if(filename == null)

            throw new IllegalArgumentException("The filename cannot be null!");

        return parent + File.separator + filename;

    }

    public static void main(String[] args) {

        System.out.println(IllegalArgumentExceptionExample.createRelativePath("dir1", "file1"));

        System.out.println();

        System.out.println(IllegalArgumentExceptionExample.createRelativePath(null, "file1"));

    }

}

A sample execution is shown below:

dir1/file1
Exception in thread "main" 

java.lang.IllegalArgumentException: The parent path cannot be null!
	at main.java.IllegalArgumentExceptionExample.createRelativePath(IllegalArgumentExceptionExample.java:15)
	at main.java.IllegalArgumentExceptionExample.main(IllegalArgumentExceptionExample.java:29)

2. How to deal with the java.lang.IllegalArgumentException

  • When the IllegalArgumentException is thrown, you must check the call stack in Java’s stack trace and locate the method that produced the wrong argument.
  • The IllegalArgumentException is very useful and can be used to avoid situations where your application’s code would have to deal with unchecked input data.

3. Download the Eclipse Project

 This was a tutorial about IllegalArgumentException in Java.

Last updated on Oct. 12th, 2021

Photo of Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.

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.

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

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.

Добавить комментарий