Java 中的 IllegalStateException 和 IllegalArgumentException 異常分別在什麼情況下丟擲?


IllegalStateException

當您在非法或不合適的時間呼叫方法時,會丟擲此異常,從而生成一個 IlleagalStateException。

例如,ArrayList 類的 remove() 方法在呼叫 next() 或 previous 方法後刪除最後一個元素。

  • 在刪除當前位置的元素後,您需要移動到下一個元素才能刪除它,即每次呼叫 next() 方法,只能呼叫一次此 remove() 方法。
  • 由於列表的初始位置(指標)將在第一個元素之前,因此在不呼叫 next 方法的情況下,您無法呼叫此方法。

如果您在其他情況下呼叫 remove() 方法,則會丟擲 java.lang.IllegalStateException 異常。

示例

在以下示例中,我們嘗試在移動到第一個元素之前,使用 remove() 方法刪除 ArrayList 的元素。

import java.util.ArrayList;
import java.util.ListIterator;
public class NextElementExample{
   public static void main(String args[]) {
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      //populating the ArrayList
      list.add("apples");
      list.add("mangoes");
      //Getting the Iterator object of the ArrayList
      ListIterator<String> it = list.listIterator();
      //Removing the element without moving to first position
      it.remove();
   }
}

執行時異常

Exception in thread "main" java.lang.IllegalStateException
   at java.util.ArrayList$Itr.remove(Unknown Source)
   at MyPackage.NextElementExample.main(NextElementExample.java:17)

IllegalArgumentException − 每當您向方法或建構函式傳遞不合適的引數時,都會丟擲 IllegalArgumentException 異常。

示例

java.sql.Date 類的 valueOf() 方法接受一個表示 JDBC 轉義格式 yyyy-[m]m-[d]d 中日期的字串,並將其轉換為 java.sql.Date 物件。但是,如果您以任何其他格式傳遞日期字串,則此方法會丟擲 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)

更新於: 2019年8月6日

1K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告