Java 中如何在"if"条件中自动处理 IllegalArgumentException?

java 8object oriented programmingprogramming

每当您将不适当的参数传递给方法或构造函数时,就会抛出 IllegalArgumentException。这是一个运行时异常,因此在编译时无需处理它。

示例

java.sql.Date 类的 valueOf() 方法接受表示 JDBC 转义格式 yyyy-[m]m-[d]d 中的日期的字符串,并将其转换为 java.sql.Date 对象。

import java.sql.Date;
import java.util.Scanner;
public class IllegalArgumentExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your date of birth in JDBC escape format (yyyy-mm-dd) ");
      String dateString = sc.next();
      Date date = Date.valueOf(dateString);
      System.out.println("Given date converted int to an object: "+date);
   }
}

输出

Enter your date of birth in JDBC escape format (yyyy-mm-dd)
1989-09-26
Given date converted into an object: 1989-09-26

但是如果您以任何其他格式传递日期字符串,则此方法将引发 IllegalArgumentException。

import java.sql.Date;
import java.util.Scanner;
public class IllegalArgumentExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your date of birth in JDBC escape format (yyyy-mm-dd) ");
      String dateString = sc.next();
      Date date = Date.valueOf(dateString);
      System.out.println("Given date converted int to an object: "+date);
   }
}

运行时异常

Enter your date of birth in JDBC escape format (yyyy-mm-dd)
26-07-1989
Exception in thread "main" java.lang.IllegalArgumentException
   at java.sql.Date.valueOf(Unknown Source)
   at july_ipoindi.NextElementExample.main(NextElementExample.java:11)
In the following Java example the Date constructor (actually deprecated) accepts

示例

Thread 类的 setPriority() 方法接受一个表示线程优先级的整数值,并将其设置为当前线程。但是,传递给此方法的值应该小于线程的最大优先级,否则,此方法将抛出 IllegalArgumentException

public class IllegalArgumentExample {
   public static void main(String args[]) {
      Thread thread = new Thread();
      System.out.println(thread.MAX_PRIORITY);
      thread.setPriority(12);
   }
}

运行时异常

10Exception in thread "main"
java.lang.IllegalArgumentException
   at java.lang.Thread.setPriority(Unknown Source)
   at july_ipoindi.NextElementExample.main(NextElementExample.java:6)

在 if 条件中处理 IllegalArgumentException

当您使用导致 IllegalArgumentException 的方法时,由于您知道它们的合法参数,因此您可以事先使用 if 条件限制/验证参数并避免异常。

示例

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

相关文章