Illegal argument exception java ошибка

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

Let’s look at IllegalArgumentException, which is one of the most common types of exceptions that Java developers deal with.

We’ll see when and why IllegalArgumentException usually occurs, whether it’s a checked or unchecked exception, as well as how to catch and when to throw it. We’ll use a few examples based on common Java library methods to describe some of the ways to handle IllegalArgumentException.

When and why does IllegalArgumentException usually occur in Java?

IllegalArgumentException is a Java exception indicating that a method has received an argument that is invalid or inappropriate for this method’s purposes.

This exception is normally used when further processing in the method depends on the invalid argument and can not continue unless a proper argument is provided instead.

IllegalArgumentException is commonly used in scenarios where the type of a method’s parameter is not sufficient to properly constrain its possible values. For example, look for an IllegalArgumentException whenever a method expects a string argument that it then internally parses to match a specific pattern.

Is IllegalArgumentException checked or unchecked?

IllegalArgumentException is an unchecked Java exception (a.k.a. runtime exception). It derives from RuntimeException, which is the base class for all unchecked exceptions in Java.

Here’s the inheritance hierarchy of IllegalArgumentException:

Throwable (java.lang)
    Exception (java.lang)
        RuntimeException (java.lang)
            IllegalArgumentException (java.lang)

Because IllegalArgumentException is an unchecked exception, the Java compiler doesn’t force you to catch it. Neither do you need to declare this exception in your method declaration’s throws clause. It’s perfectly fine to catch IllegalArgumentException, but if you don’t, the compiler will not generate any errors.

IllegalArgumentException is the most generic in a group of exceptions that indicate incorrect input data. It has a lot of inheritors in the JDK that represent more specific input errors. These include:

  • IllegalFormatException and its inheritors that are thrown when illegal syntax or format specifiers are detected in a format string.
  • InvalidPathException that is thrown when a string that is expected to represent a file system path can’t be converted into an object of type Path because it contains invalid characters.
  • NumberFormatException that is thrown when an attempt to convert a string to a numeric type fails because the string has an incompatible format.

In OpenJDK 17, the full list of exceptions derived from IllegalArgumentException is as follows:

IllegalArgumentException (java.lang)
    CSVParseException (com.sun.tools.jdeprscan)
    IllegalChannelGroupException (java.nio.channels)
    IllegalCharsetNameException (java.nio.charset)
    IllegalFormatException (java.util)
        DuplicateFormatFlagsException (java.util)
        FormatFlagsConversionMismatchException (java.util)
        IllegalFormatArgumentIndexException (java.util)
        IllegalFormatCodePointException (java.util)
        IllegalFormatConversionException (java.util)
        IllegalFormatFlagsException (java.util)
        IllegalFormatPrecisionException (java.util)
        IllegalFormatWidthException (java.util)
        MissingFormatArgumentException (java.util)
        MissingFormatWidthException (java.util)
        UnknownFormatConversionException (java.util)
        UnknownFormatFlagsException (java.util)
    IllegalSelectorException (java.nio.channels)
    IllegalThreadStateException (java.lang)
    InvalidKeyException (javax.management.openmbean)
    InvalidOpenTypeException (javax.management.openmbean)
    InvalidParameterException (java.security)
    InvalidPathException (java.nio.file)
    InvalidStreamException (com.sun.nio.sctp)
    KeyAlreadyExistsException (javax.management.openmbean)
    NumberFormatException (java.lang)
    PatternSyntaxException (java.util.regex)
    ProviderMismatchException (java.nio.file)
    SAGetoptException (sun.jvm.hotspot)
    UnresolvedAddressException (java.nio.channels)
    UnsupportedAddressTypeException (java.nio.channels)
    UnsupportedCharsetException (java.nio.charset)

How to catch IllegalArgumentException in Java

Since IllegalArgumentException is an unchecked exception, you don’t have to handle it in your code: Java will let you compile just fine.

In many cases, instead of trying to catch IllegalArgumentException, you can simply check that a value falls in the expected range before passing it to a method.

If you do choose to handle IllegalArgumentException with a try/catch block, depending on your business logic, you may want to substitute the offending argument with a default value, or modify the offending argument to make it fall inside the expected range.

When you handle IllegalArgumentException, note that it doesn’t provide any specialized methods other than those inherited from RuntimeException and ultimately from Throwable. When catching and handling an IllegalArgumentException, as with any other Java exception, you most commonly use standard Throwable methods like getMessage(), getLocalizedMessage(), getCause(), and printStackTrace().

Let’s look at an example of how you can get an IllegalArgumentException when working with common Java library code. When handling it, we’ll log the exception and retry with a default value instead of an incorrect argument.

IllegalArgumentException example 1: Unrecognized log level in Java logging API

When you work with Java’s core logging API defined in module java.util.logging, you either use predefined log levels (SEVERE, WARNING, FINE, FINER, etc.) or provide a string that is then parsed to match a known log level or an integer:

String logLevel = "SEVERE";
LOGGER.log(Level.parse(logLevel), "Processing {0} entries in a list", list.size());

If you make a typo specifying a log level in a string — for example, pass in the string "SEVER" instead of "SEVERE"the logger will not be able to parse the level and will throw IllegalArgumentException:

Exception in thread "main" java.lang.IllegalArgumentException: Bad level "SEVER"
    at java.logging/java.util.logging.Level.parse(Level.java:527)
    at com.lightrun.exceptions.Main.main(Main.java:29)

Process finished with exit code 1

You could prevent this exception altogether if you avoid parsing and stick to the predefined log levels. However, if for some reason you need to keep parsing log levels, one option would be to wrap logging in the try/catch block, and when you catch IllegalArgumentException, recover by rolling back to a default logging level:

String logLevel = "SEVER";
try {
    LOGGER.log(Level.parse(logLevel), "Processing {0} entries in a list", list.size());
} catch (IllegalArgumentException e) {
    Level defaultLogLevel = Level.WARNING;
    LOGGER.log(Level.INFO, "Provided invalid log level {0}, defaulting to INFO", logLevel);
    LOGGER.log(defaultLogLevel, "Processing {0} entries in a list", list.size());
}

IllegalArgumentException example 2: Randomizer

Java’s standard random number generator, java.util.Random, has a method nextInt(int bound) that generates a random number in a range from 0 (inclusive) to the upper bound expressed by its bound parameter (exclusive). Since the parameter is of type int, you can pass 0 or a negative integer without breaking any type system constraints. However, in the context of this method, passing any number smaller than 1 does not make sense: the generator can’t generate a random number in the range from 0 (inclusive) to 0 (exclusive), nor will it generate a number in a negative range. Consider the following method:

public static int randomize(ArrayList<Integer> list){
    Random randomGenerator = new Random();
    return randomGenerator.nextInt(list.size());
}

This method takes a list and returns a random number from 0 to the length of the list. Now, if the list has any items in it, this code will work fine, but what if the list is empty?

ArrayList<Integer> integerList = getListFromElsewhere();
System.out.printf("The size of this list is %d%n", integerList.size());
int randomInteger = randomize(integerList);

Let’s see what happens when we run this code:

The size of this list is 0
Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
    at java.base/java.util.Random.nextInt(Random.java:322)
    at com.lightrun.exceptions.RandomSample.randomize(RandomSample.java:35)
    at com.lightrun.exceptions.RandomSample.illegalArgumentExceptionWithRandomizer(RandomSample.java:15)
    at com.lightrun.exceptions.Main.main(Main.java:11)

Process finished with exit code 1

As you can see, nextInt() throws an exception that remains unhandled, and the program exits.

Suppose you’re unable to modify the randomize() method. How can you handle this on the call site?

In principle, you could throw a new runtime exception, specify the IllegalArgumentException coming from nextInt() as its cause, and communicate up the call stack that the provided list should not be empty:

int randomInteger;
try {
    randomInteger = randomize(integerList);
} catch (IllegalArgumentException illegalArgumentException) {
    String description = String.join("\n",
            "The provided list is empty (size = 0).",
            "The randomizer can't generate a random number between 0 and 0.",
            "In order to use the size of a list as the upper bound for generating random numbers,",
            "please provide a longer list."
            );
    throw new RuntimeException(description, illegalArgumentException) {
    };
}

Another solution, and probably a more practical one, would be to check if the supplied list is empty, and if so, return a fixed value instead of calling the randomize() method:

ArrayList<Integer> integerList = getListFromElsewhere();
int randomInteger = integerList.size() > 0 ? randomize(integerList) : 1;

When and how to throw IllegalArgumentException in Java

You normally throw an IllegalArgumentException when validating input parameters passed into a Java method and you need to be more strict than the type system allows.

For example, if your method accepts an integer parameter that it uses to express a percentage, then you probably need to make sure that in order to make sense, the value of that parameter is between 0 and 100. If the value falls out of that range, you can throw an IllegalArgumentException:

public static int getAbsoluteEstimateFromPercentage(double percentOfTotal) {

    int totalPopulation = 143_680_117;

    if (percentOfTotal < 0 || percentOfTotal > 100) {
        throw new IllegalArgumentException("Percentage of total should be between 0 and 100, but was %f".formatted(percentOfTotal));
    }

    return (int) Math.round(totalPopulation * (percentOfTotal * 0.01));
}

It’s important to provide meaningful exception messages to make troubleshooting easier. This is why instead of throwing an IllegalArgumentException with an empty value, we provide a message that:

  • Defines the valid range of parameter values.
  • Includes the exact value that was out of the valid range.

When you throw an IllegalArgumentException in your method, you don’t have to add it to the method’s throws clause because it’s unchecked. However, many developers tend to add selected unchecked exceptions to the throws clause anyway for documentation purposes:

public static int getAbsoluteEstimateFromPercentage(double percentOfTotal) throws IllegalArgumentException {}

Even if you do add IllegalArgumentException to throws, callers of your method will not be obliged to handle it.

An alternative way of documenting important unchecked exceptions is using the @throws Javadoc documentation tag. In fact, the Oracle guidelines on using Javadoc comments claim that including unchecked exceptions such as IllegalArgumentException into a method’s throws class is a bad programming practice and recommends using the @throws documentation tag instead:

/**
 * @param percentOfTotal Percentage of total
 * @return A rough estimate of the absolute number resulting from taking a percentage of total
 * @throws IllegalArgumentException if percentage is outside the range of 0..100
 */
public static int getAbsoluteEstimateFromPercentage(double percentOfTotal) {

How to avoid IllegalArgumentException

Because IllegalArgumentException is an unchecked exception, your IDE or Java code analysis tool will probably not help you see if code that you’re calling will throw this exception before you run your application.

What your IDE can sometimes do for you is detect if the argument that you pass to a library method is out of range for this method. If you’re using IntelliJ IDEA for Java development, it comes with a set of annotations for JDK methods: additional metadata that helps clarify how these methods should be used. Specifically, there’s a @Range annotation that describes the acceptable range of values for a method, and if you’re writing code that violates that range, the IDE will let you know.

For example, the nextInt() method of JDK’s Random type is annotated with @Range, and if you invoke the Quick Documentation popup on that method, you’ll see that it tells you about the acceptable range:

Range of nextInt() documented in IntelliJ IDEA

Even if you go ahead and pass a value to nextInt() that is known to be out of range for this method, IntelliJ IDEA will display a highlight in the code editor to warn you about the issue:

IntelliJ IDEA warns about an invalid value passed to nextInt()

However, if you’re using a method that is not annotated like this, don’t rely on your IDE: you’re on your own.

In general, when calling library methods, it’s a good practice to take note of throws clauses and @throws Javadoc documentation tags. In many cases, library developers use either or both of these tools to document why their methods could throw IllegalArgumentException.

Production debugging isn’t scary with Lightrun

Properly handling exceptions is one thing that you as a developer can do to ensure a smooth ride in production for your Java applications. Still, let’s face it: any non-trivial application will have bugs. You’re lucky if you can reproduce a bug in a local environment, debug and happily push a verified fix.

What if you can’t? Debugging remotely is tricky: you need to rely on existing logging, repeatedly redeploy updates with more logs and attempted fixes, and you’re even unable to set a proper breakpoint because you can’t afford to halt a production environment.

Take a look at Lightrun: our next-gen remote debugger for your production environment. With Lightrun, you can inject logs without changing code or redeploying, and add snapshots: breakpoints that don’t stop your production application. Lightrun supports Java, .NET, Python and Node.js applications, integrates with IntelliJ IDEA and VS Code. Set up a Lightrun account and check for yourself!

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:

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!

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!

An IllegalArgumentException is thrown in order to indicate that a method has been passed an illegal argument. 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.

Reasons for java.lang.IllegalArgumentException

  • When Arguments out of range. For example, the percentage should lie between 1 to 100. If the user entered 101 then an IllegalArugmentExcpetion will be thrown.
  • When argument format is invalid. For example, if our method requires date format like YYYY/MM/DD but if the user is passing YYYY-MM-DD. Then our method can’t understand then IllegalArugmentExcpetion will be thrown.
  • When a method needs non-empty string as a parameter but the null string is passed.

Example1

public class Student {
   int m;
   public void setMarks(int marks) {
      if(marks < 0 || marks > 100)
         throw new IllegalArgumentException(Integer.toString(marks));
      else
         m = marks;
   }
   public static void main(String[] args) {
      Student s1 = new Student();
      s1.setMarks(45);
      System.out.println(s1.m);
      Student s2 = new Student();
      s2.setMarks(101);
      System.out.println(s2.m);
   }
}

Output

45
Exception in thread "main" java.lang.IllegalArgumentException: 101
at Student.setMarks(Student.java:5)
at Student.main(Student.java:15)

Steps to solve IllegalArgumentException

  • When an IllegalArgumentException is thrown, we 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 the application’s code would have to deal with unchecked input data.
  • The main use of this IllegalArgumentException is for validating the inputs coming from other 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.

Example2

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)
                  throw new IllegalArgumentException("value must be non-negative and below 100");
               System.out.println( marks);
            }
            catch(IllegalArgumentException i) {
               System.out.println("out of range encouneterd. Want to continue");
               cont = scan.next();  
               if(cont.equalsIgnoreCase("Y"))
                   run(cont);
               }
          }
     }
}

Output

Enter an integer:
1
1
Enter an integer:
100
100
Enter an integer:
150
out of range encouneterd. Want to continue
y
Enter an integer:

Can anyone explain to me why this error occures, or even better how do I handle it? I can not reproduce it. It is one of those errors that happends once out of a 1000.

Background: The user is trying to log in, a progress dialog is showing, a http request is sent in async task, the progress dialog is dissmissed. Error occures, app FC.

LoginActivity.java

 255:   private void dismissProgress() {  
 256:     if (mProgress != null) {  
 257:         mProgress.dismiss();  
 258:         mProgress = null;  
 259:     }  
 260:   }  

java.lang.IllegalArgumentException: View not attached to window manager
at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:391)
at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:236)
at android.view.Window$LocalWindowManager.removeView(Window.java:432)
at android.app.Dialog.dismissDialog(Dialog.java:278)
at android.app.Dialog.access$000(Dialog.java:71)
at android.app.Dialog$1.run(Dialog.java:111)
at android.app.Dialog.dismiss(Dialog.java:268)
at se.magpern.LoginActivity.dismissProgress(LoginActivity.java:257)
at se.magpern.LoginActivity.access$5(LoginActivity.java:255)
at se.magpern.LoginActivity$DoTheLogin.onPostExecute(LoginActivity.java:293)
at se.magpern.LoginActivity$DoTheLogin.onPostExecute(LoginActivity.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:417)
at android.os.AsyncTask.access$300(AsyncTask.java:127)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:144)
at android.app.ActivityThread.main(ActivityThread.java:4937)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)

EboMike's user avatar

EboMike

76.3k14 gold badges161 silver badges167 bronze badges

asked Feb 14, 2011 at 23:40

Magnus's user avatar

2

This can happen if the user either dismisses the view (e.g. a dialog that can be backed out of) or if the user switches to a different activity while your task is running. You should seriously think about using Android’s activity-native dialog showing/dismissing instead of trying to keep a reference to the views yourself. But if you are handling it yourself, you may want to check if the dialog is actually showing using the dialog’s isShowing() method before trying to dismiss it.

answered Feb 15, 2011 at 2:34

Yoni Samlan's user avatar

Yoni SamlanYoni Samlan

37.7k5 gold badges60 silver badges62 bronze badges

2

I’ve seen this happen when a latent update comes in for a progress dialog that has already been fully or partially dismissed. Either the user is requesting a dismissal at the same time the os is trying to dismiss the view and its already been disconnected from the window or vice versa.

There is a race condition between the code that dismisses the progress window when a button is clicked and the code that dismisses the progress window in another fashion. The mostly likely place to look for this race condition is where your requests for dismissing the windows are put onto the view thread (button handler or a code callback).

answered Feb 14, 2011 at 23:44

Nick Campion's user avatar

Nick CampionNick Campion

10.5k3 gold badges44 silver badges58 bronze badges

4

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.

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ilife v55 робот пылесос ошибка e04
  • Immergas ошибка е44
  • Iis включить отображение ошибок
  • Igfxtray exe ошибка приложения
  • Ilife v55 ошибка е06 что делать

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

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: