在使用导致IllegalArgumentException的方法时,由于您知道它们的合法参数,因此可以事先使用if-condition限制/验证参数,并避免出现异常。
我们可以使用if语句限制方法的参数值。例如,如果某个方法接受某个范围的值,则可以在执行该方法之前使用if语句验证参数的范围。
以下示例setPriority()使用if语句处理由方法引起的IllegalArgumentException 。
import java.util.Scanner; public class IllegalArgumentExample { public static void main(String args[]) { Thread thread = new Thread(); System.out.println("输入线程优先级值: "); Scanner sc = new Scanner(System.in); int priority = sc.nextInt(); if(priority<=Thread.MAX_PRIORITY) { thread.setPriority(priority); }else{ System.out.println("优先级值应小于: "+Thread.MAX_PRIORITY); } } }输出结果
输入线程优先级值: 15 优先级值应小于: 10