What is an illegal argument exception in java

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.
Читайте также:  Forums viewtopic php данного

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.

Читайте также:  scale()

Источник

What is an illegal argument exception in java

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 Detail

IllegalArgumentException

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

Источник

How to Throw IllegalArgumentException in Java

How to Throw IllegalArgumentException in 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 IllegalArgumentException code> 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.
Читайте также:  Schengen calculator en html

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 age code> argument set to -1. Since setAge() code> expects age to be a positive number, it throws an IllegalArgumentException code>:

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.

«Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.»

Источник

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