Java 中何時會丟擲 IllegalStateException(非受檢異常)?
IllegalStateException 是 Java 中的非受檢異常。如果處理的是java.util 包的集合框架,則 Java 程式中可能會出現此異常。有很多集合,例如List、Queue、Tree、Map,其中List和Queue(Queue 和 Deque)會在特定條件下丟擲此IllegalStateException。
何時會丟擲 IllegalStateException
- 當嘗試在不合適的時間呼叫特定方法時,將丟擲IllegalStateException異常。
- 對於java.util.List 集合,我們使用ListIterator介面的next()方法遍歷java.util.List。如果在呼叫next()方法之前呼叫ListIterator介面的remove()方法,則會丟擲此異常,因為它會使List集合處於不穩定狀態。
- 如果要修改特定物件,將使用ListIterator介面的set()方法。
- 對於佇列,如果嘗試向佇列新增元素,則必須確保佇列未滿。如果佇列已滿,則無法新增該元素,這將導致丟擲IllegalStateException異常。
示例
import java.util.*;
public class IllegalStateExceptionTest {
public static void main(String args[]) {
List list = new LinkedList();
list.add("Welcome");
list.add("to");
list.add("Tutorials");
list.add("Point");
ListIterator lIterator = list.listIterator();
lIterator.next();
lIterator.remove();// modifying the list
lIterator.set("Tutorix");
System.out.println(list);
}
}輸出
Exception in thread "main" java.lang.IllegalStateException at java.util.LinkedList$ListItr.set(LinkedList.java:937) at IllegalStateExceptionTest.main(IllegalStateExceptionTest.java:15)
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP