Java main argument exception

java.lang.IllegalArgumentException – Reasons and How to Solve?

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.

Reasons for java.lang.IllegalArgumentException

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.


How to Throw IllegalArgumentException in Java

Table of Contents

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.

IllegalArgumentException Example

Here is an example of a IllegalArgumentException thrown when the argument passed to a method is out of range:

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

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](×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.


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.


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.

Читайте также:  Apk install unknown error

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:


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

Posted by: Sotirios-Efstathios Maneas in exceptions March 20th, 2014 0 Views

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.


Java main argument exception

Table of Contents

When a program violates the semantic constraints of the Java programming language, the Java Virtual Machine signals this error to the program as an exception .

An example of such a violation is an attempt to index outside the bounds of an array. Some programming languages and their implementations react to such errors by peremptorily terminating the program; other programming languages allow an implementation to react in an arbitrary or unpredictable way. Neither of these approaches is compatible with the design goals of the Java SE platform: to provide portability and robustness.

Instead, the Java programming language specifies that an exception will be thrown when semantic constraints are violated and will cause a non-local transfer of control from the point where the exception occurred to a point that can be specified by the programmer.

An exception is said to be thrown from the point where it occurred and is said to be caught at the point to which control is transferred.

Programs can also throw exceptions explicitly, using throw statements (§14.18).

Explicit use of throw statements provides an alternative to the old-fashioned style of handling error conditions by returning funny values, such as the integer value -1 where a negative value would not normally be expected. Experience shows that too often such funny values are ignored or not checked for by callers, leading to programs that are not robust, exhibit undesirable behavior, or both.

Every exception is represented by an instance of the class Throwable or one of its subclasses (§11.1). Such an object can be used to carry information from the point at which an exception occurs to the handler that catches it. Handlers are established by catch clauses of try statements (§14.20).

Читайте также:  Core ndss http error 401 authentication failed

During the process of throwing an exception, the Java Virtual Machine abruptly completes, one by one, any expressions, statements, method and constructor invocations, initializers, and field initialization expressions that have begun but not completed execution in the current thread. This process continues until a handler is found that indicates that it handles that particular exception by naming the class of the exception or a superclass of the class of the exception (§11.2). If no such handler is found, then the exception may be handled by one of a hierarchy of uncaught exception handlers (§11.3) — thus every effort is made to avoid letting an exception go unhandled.

The exception mechanism of the Java SE platform is integrated with its synchronization model (§17.1), so that monitors are unlocked as synchronized statements (§14.19) and invocations of synchronized methods (§, §15.12) complete abruptly.

11.1. The Kinds and Causes of Exceptions

11.1.1. The Kinds of Exceptions

An exception is represented by an instance of the class Throwable (a direct subclass of Object ) or one of its subclasses.

Throwable and all its subclasses are, collectively, the exception classes .

The classes Exception and Error are direct subclasses of Throwable :

Exception is the superclass of all the exceptions from which ordinary programs may wish to recover.

The class RuntimeException is a direct subclass of Exception . RuntimeException is the superclass of all the exceptions which may be thrown for many reasons during expression evaluation, but from which recovery may still be possible.

RuntimeException and all its subclasses are, collectively, the run-time exception classes .

Error is the superclass of all the exceptions from which ordinary programs are not ordinarily expected to recover.

Error and all its subclasses are, collectively, the error classes .

The unchecked exception classes are the run-time exception classes and the error classes.

The checked exception classes are all exception classes other than the unchecked exception classes. That is, the checked exception classes are Throwable and all its subclasses other than RuntimeException and its subclasses and Error and its subclasses.

Programs can use the pre-existing exception classes of the Java SE platform API in throw statements, or define additional exception classes as subclasses of Throwable or of any of its subclasses, as appropriate. To take advantage of compile-time checking for exception handlers (§11.2), it is typical to define most new exception classes as checked exception classes, that is, as subclasses of Exception that are not subclasses of RuntimeException .

The class Error is a separate subclass of Throwable , distinct from Exception in the class hierarchy, to allow programs to use the idiom » > catch (Exception e) < " (§11.2.3) to catch all exceptions from which recovery may be possible without catching errors from which recovery is typically not possible.

Note that a subclass of Throwable cannot be generic (§8.1.2).

11.1.2. The Causes of Exceptions

An exception is thrown for one of three reasons:

A throw statement (§14.18) was executed.

An abnormal execution condition was synchronously detected by the Java Virtual Machine, namely:

evaluation of an expression violates the normal semantics of the Java programming language (§15.6), such as an integer divide by zero.

an error occurs while loading, linking, or initializing part of the program (§12.2, §12.3, §12.4); in this case, an instance of a subclass of LinkageError is thrown.

an internal error or resource limitation prevents the Java Virtual Machine from implementing the semantics of the Java programming language; in this case, an instance of a subclass of VirtualMachineError is thrown.

These exceptions are not thrown at an arbitrary point in the program, but rather at a point where they are specified as a possible result of an expression evaluation or statement execution.

An asynchronous exception occurred (§11.1.3).

11.1.3. Asynchronous Exceptions

Most exceptions occur synchronously as a result of an action by the thread in which they occur, and at a point in the program that is specified to possibly result in such an exception. An asynchronous exception is, by contrast, an exception that can potentially occur at any point in the execution of a program.

Asynchronous exceptions occur only as a result of:

An invocation of the (deprecated) stop method of class Thread or ThreadGroup .

The (deprecated) stop methods may be invoked by one thread to affect another thread or all the threads in a specified thread group. They are asynchronous because they may occur at any point in the execution of the other thread or threads.

Читайте также:  Delphi internal error t2335

An internal error or resource limitation in the Java Virtual Machine that prevents it from implementing the semantics of the Java programming language. In this case, the asynchronous exception that is thrown is an instance of a subclass of VirtualMachineError .

Note that StackOverflowError , a subclass of VirtualMachineError , may be thrown synchronously by method invocation (§ as well as asynchronously due to native method execution or Java Virtual Machine resource limitations. Similarly, OutOfMemoryError , another subclass of VirtualMachineError , may be thrown synchronously during class instance creation (§15.9.4, §12.5), array creation (§15.10.2, §10.6), class initialization (§12.4.2), and boxing conversion (§5.1.7), as well as asynchronously.

The Java SE platform permits a small but bounded amount of execution to occur before an asynchronous exception is thrown.

Asynchronous exceptions are rare, but proper understanding of their semantics is necessary if high-quality machine code is to be generated.

The delay noted above is permitted to allow optimized code to detect and throw these exceptions at points where it is practical to handle them while obeying the semantics of the Java programming language. A simple implementation might poll for asynchronous exceptions at the point of each control transfer instruction. Since a program has a finite size, this provides a bound on the total delay in detecting an asynchronous exception. Since no asynchronous exception will occur between control transfers, the code generator has some flexibility to reorder computation between control transfers for greater performance. The paper Polling Efficiently on Stock Hardware by Marc Feeley, Proc. 1993 Conference on Functional Programming and Computer Architecture, Copenhagen, Denmark, pp. 179-187, is recommended as further reading.

11.2. Compile-Time Checking of Exceptions

The Java programming language requires that a program contains handlers for checked exceptions which can result from execution of a method or constructor (§8.4.6, §8.8.5). This compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions which are not properly handled. For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class of that exception or one of the superclasses of the class of that exception (§11.2.3).

The checked exception classes (§11.1.1) named in the throws clause are part of the contract between the implementor and user of the method or constructor. The throws clause of an overriding method may not specify that this method will result in throwing any checked exception which the overridden method is not permitted, by its throws clause, to throw (§ When interfaces are involved, more than one method declaration may be overridden by a single overriding declaration. In this case, the overriding declaration must have a throws clause that is compatible with all the overridden declarations (§9.4.1).

The unchecked exception classes (§11.1.1) are exempted from compile-time checking.

Error classes are exempted because they can occur at many points in the program and recovery from them is difficult or impossible. A program declaring such exceptions would be cluttered, pointlessly. Sophisticated programs may yet wish to catch and attempt to recover from some of these conditions.

Run-time exception classes are exempted because, in the judgment of the designers of the Java programming language, having to declare such exceptions would not aid significantly in establishing the correctness of programs. Many of the operations and constructs of the Java programming language can result in exceptions at run time. The information available to a Java compiler, and the level of analysis a compiler performs, are usually not sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious to the programmer. Requiring such exception classes to be declared would simply be an irritation to programmers.

For example, certain code might implement a circular data structure that, by construction, can never involve null references; the programmer can then be certain that a NullPointerException cannot occur, but it would be difficult for a Java compiler to prove it. The theorem-proving technology that is needed to establish such global properties of data structures is beyond the scope of this specification.

We say that a statement or expression can throw an exception class E if, according to the rules in §11.2.1 and §11.2.2, the execution of the statement or expression can result in an exception of class E being thrown.

We say that a catch clause can catch its catchable exception class(es):

The catchable exception class of a uni- catch clause is the declared type of its exception parameter (§14.20).

The catchable exception classes of a multi- catch clause are the alternatives in the union that denotes the type of its exception parameter.


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