如何在 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

更新时间: 2021-02-08

527 次查看

开启你的 事业

完成课程即可获得认证

开始
广告