IllegalArgumentException ถูกโยนเพื่อระบุว่าเมธอดถูกส่งผ่าน illegal argument Exception นี้ extends RuntimeException class และจึงเป็น exceptions ที่อาจโยนระหว่างการทำงานของ JVM เป็น unchecked exception จึงไม่ต้องประกาศใน throws clause ของเมธอดหรือคอนสตรัคเตอร์
เหตุผลของ java.lang.IllegalArgumentException
- เมื่อ Arguments out of range เช่น percentage ควรอยู่ 1-100 หาก user ป้อน 101 จะโยน IllegalArgumentException
- เมื่อ argument format ไม่ถูกต้อง เช่น เมธอดต้องการ date format YYYY/MM/DD แต่ user ส่ง YYYY-MM-DD เมธอดไม่เข้าใจ จึงโยน IllegalArgumentException
- เมื่อเมธอดต้องการ non-empty string เป็น parameter แต่ส่ง null string
ตัวอย่างที่ 1
public class Student {
int m;
public void setMarks(int marks) {
if(marks < 0 || marks > 100)
throw new IllegalArgumentException(Integer.toString(marks));
else
m = marks;
}
public static void main(String[] args) {
Student s1 = new Student();
s1.setMarks(45);
System.out.println(s1.m);
Student s2 = new Student();
s2.setMarks(101);
System.out.println(s2.m);
}
}
ผลลัพธ์
45
Exception in thread "main" java.lang.IllegalArgumentException: 101
at Student.setMarks(Student.java:5)
at Student.main(Student.java:15)
ขั้นตอนแก้ไข IllegalArgumentException
- เมื่อ IllegalArgumentException ถูกโยน เราต้องตรวจสอบ call stack ใน Java stack trace และหาเมธอดที่สร้าง wrong argument
- IllegalArgumentException มีประโยชน์มาก สามารถใช้ป้องกันสถานการณ์ที่ application code ต้องจัดการ unchecked input data
- การใช้งานหลักของ IllegalArgumentException คือ validation inputs ที่มาจากผู้ใช้อื่น
- ถ้าต้องการ catch IllegalArgumentException ใช้ try-catch blocks การทำเช่นนี้ช่วยจัดการบางสถานการณ์ สมมติใน catch block ใส่โค้ดให้โอกาส user ป้อนใหม่ แทนที่จะหยุด execution โดยเฉพาะในกรณี looping
ตัวอย่างที่ 2
import java.util.Scanner;
public class Student {
public static void main(String[] args) {
String cont = "y";
run(cont);
}
static void run(String cont) {
Scanner scan = new Scanner(System.in);
while( cont.equalsIgnoreCase("y")) {
try {
System.out.println("Enter an integer: ");
int marks = scan.nextInt();
if (marks < 0 || marks > 100)
throw new IllegalArgumentException("value must be non-negative and below 100");
System.out.println(marks);
}
catch(IllegalArgumentException i) {
System.out.println("out of range encountered. Want to continue");
cont = scan.next();
if(cont.equalsIgnoreCase("Y"))
run(cont);
}
}
}
}
ผลลัพธ์
Enter an integer: 1 1 Enter an integer: 100 100 Enter an integer: 150 out of range encountered. Want to continue y Enter an integer: