Wednesday, 15 February 2012

How to solve IllegalArgumentException in java with examples

Fix for IllegalArgumentException in java:-


IllegalArgumentException is one of frequent exceptions occured in java programming language. This exception extends RunTimeException class. These are also called UncheckedExceptions and need not to be handled in java code for this exceptions occurs at runtime. Exceptions in java are used to indicate that there is an error in your code.

IllegalArgumentException is good way of handling in the code.This exception occurs when caller calling method with incorrect arugment types for the methods. Methods in java are written in such way that we have to deal with valid data as well as invalid data,if it is valid data,process the data,and result is returned.In case of bad data, we have to throws this exception with detailed message to the caller. This is good way of handling invalid data with approriate 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 exception is thrown.

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


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

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

When to throws IllegalArgumentException :-
This exception throwns for invalid arguments types for the below values

1.When object as 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.

0 comments:

Post a Comment