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); } }
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
输出
Exception in thread "main" java.lang.IllegalStateException at java.util.LinkedList$ListItr.set(LinkedList.java:937) at IllegalStateExceptionTest.main(IllegalStateExceptionTest.java:15)
广告