Java error illegal argument

How to solve an IllegalArgumentException in Java?

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.
Читайте также:  Sqlite3 python autoincrement primary key

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:

Источник

Class IllegalArgumentException

Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause ).

Method Summary

Methods declared in class java.lang.Throwable

Methods declared in class java.lang.Object

Constructor Details

IllegalArgumentException

IllegalArgumentException

IllegalArgumentException

Constructs a new exception with the specified detail message and cause. Note that the detail message associated with cause is not automatically incorporated in this exception’s detail message.

IllegalArgumentException

Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause ). This constructor is useful for exceptions that are little more than wrappers for other throwables (for example, PrivilegedActionException ).

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Читайте также:  Interface for python program

Источник

How to Solve IllegalArgumentException in Java?

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

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.lang.IllegalArgumentException – How to solve Illegal Argument Exception

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:

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).

1. The IllegalArgumentException in Java

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

Источник

java.lang.IllegalArgumentException – How to solve Illegal Argument Exception

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:

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).

1. The IllegalArgumentException in Java

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

Источник

Оцените статью