修复java中的IllegalArgumentException:
IllegalArgumentException是java编程语言中经常出现的异常之一。这个异常扩展了RunTimeException类。这也被称为 "未检查异常"(UncheckedExceptions),在java代码中不需要处理,因为这种异常发生在运行时。java中的异常是用来表示你的代码中存在错误的。
IllegalArgumentException是在代码中处理的好方法。当调用者在调用方法时使用了不正确的语法类型,这种异常就会发生。java中的方法是这样写的,我们必须处理有效的数据和无效的数据,如果是有效的数据,就处理数据,然后返回结果。如果是坏的数据,我们必须抛出这个异常,并向调用者提供详细的信息。这是处理无效数据的好方法,并向调用者提供适当的信息,然后调用者应该向方法传递正确的数据。
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.
线程 "main "中出现异常 java.lang.IllegalArgumentException。Number 2 can't be zero 0
at MathServiceImpl.divide(IllegalExceptionDemo.java:19)
at IllegalExceptionDemo.main(IllegalExceptionDemo.java:9)
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.