Java 中 'if' 條件語句內如何自動處理 IllegalArgumentException?


當您向方法或建構函式傳遞不合適的引數時,會丟擲 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

更新於:2020年7月2日

833 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告