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 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!
Summary:
Ctors
| Inherited Methods
public
class
IllegalArgumentException
extends RuntimeException
java.lang.Object | ||||
↳ | java.lang.Throwable | |||
↳ | java.lang.Exception | |||
↳ | java.lang.RuntimeException | |||
↳ | java.lang.IllegalArgumentException |
Known direct subclasses
IllegalChannelGroupException, IllegalCharsetNameException, IllegalFormatException, IllegalSelectorException, IllegalThreadStateException, InvalidParameterException, InvalidPathException, NumberFormatException, PatternSyntaxException, ProviderMismatchException, SystemUpdatePolicy.ValidationFailedException, UnresolvedAddressException, UnsupportedAddressTypeException, UnsupportedCharsetException
Known indirect subclasses
DuplicateFormatFlagsException, FormatFlagsConversionMismatchException, IllegalFormatCodePointException, IllegalFormatConversionException, IllegalFormatFlagsException, IllegalFormatPrecisionException, IllegalFormatWidthException, MissingFormatArgumentException, MissingFormatWidthException, UnknownFormatConversionException, UnknownFormatFlagsException
Thrown to indicate that a method has been passed an illegal or
inappropriate argument.
Summary
Public constructors |
---|
Constructs an |
Constructs an |
Constructs a new exception with the specified detail message and |
Constructs a new exception with the specified cause and a detail |
Inherited methods |
||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
From class java.lang.Throwable
|
||||||||||||||||||||||||||
From class java.lang.Object
|
Public constructors
IllegalArgumentException
public IllegalArgumentException ()
Constructs an IllegalArgumentException
with no
detail message.
IllegalArgumentException
public IllegalArgumentException (String s)
Constructs an IllegalArgumentException
with the
specified detail message.
Parameters | |
---|---|
s |
String : the detail message. |
IllegalArgumentException
public IllegalArgumentException (String message, Throwable cause)
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.
Parameters | |
---|---|
message |
String : the detail message (which is saved for later retrievalby the Throwable#getMessage() method). |
cause |
Throwable : the cause (which is saved for later retrieval by theThrowable#getCause() method). (A null valueis permitted, and indicates that the cause is nonexistent or unknown.) |
IllegalArgumentException
public IllegalArgumentException (Throwable cause)
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
).
Parameters | |
---|---|
cause |
Throwable : the cause (which is saved for later retrieval by theThrowable#getCause() method). (A null value ispermitted, and indicates that the cause is nonexistent or unknown.) |
Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
Last updated 2023-02-08 UTC.
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
76.3k14 gold badges161 silver badges167 bronze badges
asked Feb 14, 2011 at 23:40
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 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 CampionNick Campion
10.5k3 gold badges44 silver badges58 bronze badges
4
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?
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
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:
- 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. - 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. - 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 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:
- Inspect the exception stack trace and identify the method that passes the illegal argument.
- Update the code to make sure that the passed argument is valid within the method that uses it.
- 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.
Сбои — головная боль для всех вовлеченных. Команды разработки ненавидят разбираться с ними, а пользователи не желают мириться — 62% пользователей удаляют приложение в случае сбоев, говорит исследование DCI. Нестабильность приложения может быстро привести к провалу всего проекта или, по крайней мере, дорого обойтись. Чтобы свести к минимуму сбои приложения и время, необходимое для их устранения, мы собрали наиболее распространенные ошибки Android-приложений и способы их устранения.
5 самых распространенных ошибок в Android-приложениях и способы их устранения
java.lang.NullPointerException
Определенно, самый частый креш в Android. Скорее всего, если вы когда-либо разрабатывали приложение для Android, то сталкивались с этой ошибкой. Наиболее частой причиной NullPointerException является ссылка на данные после выхода за пределы области видимости или сборки мусора.
Обычно это происходит, когда приложение переходит в фоновый режим, и избавляется от ненужной памяти. Это приводит к потере некоторых ссылок, и когда метод Android onResume () вызывается снова, это может привести к ошибке NullPointException.
Чтобы точно определить, где произошла ошибка, используйте трассировку стека. И, чтобы избежать ошибки и потери данных, вы должны стремиться сохранить свои данные в более надежном месте, когда вызывается метод onPause(). Просто вытащите их обратно при вызове onResume(). И, в общем, старайтесь обрабатывать любые потенциальные нулевые указатели, которые могут вызвать ошибку.
java.lang.IllegalStateException
Одна из наиболее распространенных ошибок Android-приложений, имеющих дело с Фрагментами. Ошибка IllegalStateException может происходить по множеству причин, но в основе ее лежит неправильное управление состояниями Activity.
Она возникает, когда в фоновом потоке выполняется трудоемкая операция, но тем временем создается новый Фрагмент, который отсоединяется от Activity до завершения фонового потока. Это приводит к вызову отсоединенного фрагмента и появлению такого исключения.
Чтобы решить эту проблему, вы должны отменить фоновый поток при приостановке или остановке Фрагмента. Кроме того, вы можете использовать метод isAdded(), чтобы проверить, прикреплен ли Фрагмент, а затем использовать getResources() из Activity.
java.lang.IndexOutOfBoundsException
IndexOutOfBoundsException — одно из самых распространенных исключений RunTimeExceptions, с которыми вы можете столкнуться. Эта ошибка указывает на то, что какой-либо индекс (обычно в массиве, но может быть и в строке или векторе) находится вне допустимого диапазона.
Есть несколько распространенных причин возникновения этого сбоя — использование отрицательного индекса с массивами, charAt или функцией substring. Также, если beginIndex меньше 0 или endIndex больше длины входной строки, или beginIndex больше endIndex. Другая причина — когда endIndex — beginIndex меньше 0. Но, вероятно, наиболее распространенная причина — когда входной массив (строка/вектор) пуст.
Исправить эту проблему относительно просто, всегда лучше проверять трассировку стека всякий раз, когда возникает ошибка. Первым ключевым шагом является понимание того, что вызвало сбой. После этого нужно убедиться, что этот массив, строка или вектор соответствуют требуемому индексу.
java.lang.IllegalArgumentException
Вероятно, наиболее общая причина сбоя в списке — исключение IllegalArgumentException. Самое простое его определение заключается в том, что ваш аргумент неправильный. Этому может быть много причин. Однако есть несколько общих правил.
Одна из наиболее частых причин — попытка получить доступ к элементам пользовательского интерфейса непосредственно из фонового потока. Также, если вы пытаетесь использовать переработанное растровое изображение. Другая распространенная причина — вы забыли добавить Activity в Manifest. Это не будет показано компилятором, так как это RuntimeException.
Чтобы предотвратить этот сбой, сосредоточьтесь на том, чтобы кастинг всегда был правильный. Компилятор не отлавливает множество ошибок, поэтому вам нужно проявлять понимание при обращении к ресурсам, поскольку, например, многие методы пользовательского интерфейса принимают как строки, так и целые числа.
java.lang.OutOfMemoryError
И последний, но не менее важный в нашем списке — один из самых неприятных крешей. Устройства Android бывают всех форм и с разным объемом памяти. Часто бывает, что вы имеете дело с ограниченными ресурсами. OutOfMemoryError возникает, когда ОС необходимо освободить память для высокоприоритетных операций, и она берется из выделенной вашему приложению кучи. Управление памятью становится проще, поскольку новые устройства имеют гораздо больше памяти. Однако не все пользователи вашего приложения будут работать с ними.
Что касается самой ошибки, то одна из основных причин утечки памяти, приводящей к OutOfMemoryError, — это слишком долгое сохранение ссылки на объект. Это может привести к тому, что ваше приложение будет использовать намного больше памяти, чем необходимо. Одна из наиболее распространенных причин — растровые изображения, которые в настоящее время могут быть большого размера. Поэтому не забудьте утилизировать любой объект, который возможно, когда он больше не нужен.
Вы можете запросить у ОС больше памяти для кучи, добавив в свой файл манифеста атрибут
android:largeHeap="true"
Однако это не рекомендуется, кроме случаев крайней необходимости, поскольку это всего лишь запрос и он может быть отклонен.
Источник
Если вы нашли опечатку — выделите ее и нажмите Ctrl + Enter! Для связи с нами вы можете использовать info@apptractor.ru.
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: