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.

Output

The main use of this IllegalArgumentException is for validating the inputs coming from other sites or 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.

Example Program:

Output

Comment below if you have queries or found any mistake in above tutorial for java.lang.IllegalArgumentException.

Leave a Comment

Your email address will not be published. Required fields are marked *