如何在 if 中使用 Java 处理 IllegalArgumentException
由于您了解方法的合法参数,因此在使用导致 IllegalArgumentException 的方法时,您可以预先使用 if 条件限制/验证参数,并避免发生异常。
我们可以使用 if 语句限制方法的参数值。例如,如果某个方法接受特定范围内的值,则可以在执行方法之前使用 if 语句验证参数的范围。
示例
以下示例使用 if 语句处理了 setPriority() 方法导致的 IllegalArgumentException。
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);
}
}
}输出
Enter the thread priority value: 15 Priority value should be less than: 10
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP