How to solve IllegalArgumentException in java with examples

Fix for IllegalArgumentException in java:-

IllegalArgumentException is one of the frequent exceptions that occurred in a java programming language. This exception extends RunTimeException class. These are also called UncheckedExceptions and need not be handled in java code for these exceptions occur at runtime.

Exceptions in java are used to indicate that there is an error in your code.

IllegalArgumentException is a good way of handling the code. This exception occurs when a caller calls the method with incorrect argument types for the methods.

Methods in java are written in such a way that we have to deal with valid data as well as invalid data, if it is valid data, process the data, and the result is returned. In case of bad data, we have to throw this exception with a detailed message to the caller.

This is a good way of handling invalid data with an appropriate message to the caller, then the caller should pass the correct data to the method.,

public class IllegalExceptionDemo {
   public static void main(String\[\] args) {
 MathServiceImpl service=new MathServiceImpl();
 System.out.println(" value "+service.divide(12,0));
 }
}
class MathServiceImpl {
 public int divide(int number1,int number2)
 {if(number2<=0){
    throw new  IllegalArgumentException("Number 2 can not be zero "+number2);
 }
    return number1/number2;
 }
}

The above code throws IllegalArgumentException when an argument is passed with zero values and the error message looks like as follows.

Exception in thread "main" java.lang.IllegalArgumentException: Number 2 can not be zero 0
 at MathServiceImpl.divide(IllegalExceptionDemo.java:19)
 at IllegalExceptionDemo.main(IllegalExceptionDemo.java:9)

Whenever any expceiton occurs, please see the complete stack trace for debugging, stack trace gives the exception type(IllegalArgumentException), detailed message(Number 2 can not be zero 0) and line number of the code(IllegalExceptionDemo.java:19) where an exception is thrown.

method divide() is throwing an exception when an argument(number2 is zero) using throw keyword IllegalArgulme the called method should have to handle the exception, throws this exception to the caller with a proper message. Caller method need not be handled this exception as this is a runtime exception

In programming, IllegalArgumentExceptions are coded in the following scenarios to validate the invalid arguments for methods.

  1. Service API methods
  2. Setters
  3. Constructors
  4. Unit testing

When to throws IllegalArgumentException:- This exception is thrown for invalid arguments types for the below values.

  1. When object as an argument in methods should check for null references before accessing the object methods
  2. Invalid data check for methods arguments like checking for valid numbers, custom data check.

Please share your thoughts on how do you handle this exception.