Khi dùng method gây IllegalArgumentException, vì biết các argument hợp lệ, có thể validate/restrict argument bằng if-condition trước để tránh exception.
Có thể giới hạn giá trị argument của method dùng if statement. Ví dụ: method chỉ chấp nhận giá trị trong khoảng nhất định → kiểm tra range bằng if trước khi gọi method.
Ví dụ - Xử lý setPriority()
import java.util.Scanner;
public class IllegalArgumentExample {
public static void main(String args[]) {
Thread thread = new Thread();
System.out.println("Enter the thread priority value: ");
Scanner sc = new Scanner(System.in);
int priority = sc.nextInt();
if (priority <= Thread.MAX_PRIORITY) {
thread.setPriority(priority);
} else {
System.out.println("Priority value should be less than: " + Thread.MAX_PRIORITY);
}
}
}
Đầu ra
Enter the thread priority value: 15 Priority value should be less than: 10