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!
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
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