[Java] How to causes and solve an IllegalArgumentException


At first

The cause and solve for IllegalArgumentException is very simple.
Once you understand the basics, you can easily fix it.

What is IllegalArgumentException?

Exception thrown to indicate that invalid or inappropriate arguments were passed to a method.

For example, a value greater than or equal to 0 should be passed, but it will throw if a negative number is passed.


Let’s check the cause of occurrence with concrete code.

example case

As an example, set “-1” to the setLastModified method of the File class.

throw exception

Doing so will result in an IllegalArgumentException.


The reason is that the setLastModified method raised an IllegalArgumentException for numbers less than 0.


It is necessary to pass the value of the condition under which IllegalArgumentExceptiong does not occur to the method.
In the above example, you pass a value greater than or equal to 0 to the setLastModifiedTime method.

If an IllegalArgumentExceptiong occurs, you can check the location where it occurred in the stack trace (output such as [throw exception]), and the location where it occurred is also written, so it is easy to follow.

Since the occurrence conditions are also written, it is only necessary to prevent inappropriate values from entering.

How to use IllegalArgumentException in your own class

If you want to create your own class and raise an IllegalArgumentException in it, do the following.

example 4 patterns

There are 4 patterns that combine the presence or absence of a message when an exception occurs and whether or not to pass the exception that causes it.

Basically, I personally think that there are many patterns that just add a message to the IllegalArgumentException.

If you need details of the cause of the occurrence, you can set a new exception as shown in the example above, so please use it as necessary.


  • An IllegalArgumentException is an exception thrown to indicate that you passed an invalid or inappropriate argument to a method.
  • The cause is due to an invalid value being entered in the method.
  • The solution is to follow from where it happened, check for appropriate values, and control the values that are passed.
  • It is possible to throw an exception in your own class.
    Also, when throwing, you can select whether to set a new exception that causes a message or not

Refer to

This is a book that can deepen your understanding of exceptions.

Exceptions in Java: Basics, advanced concepts, and real API examples (English Edition)


Let's share this post !

Author of this article


To comment