MENU

[Java] How to causes and solve an IllegalArgumentException

当ページのリンクには広告が含まれています。
TOC

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.

Cause

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.

why?

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

Solve

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.

Conclusion

  • 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

Comments

To comment

CAPTCHA


TOC