Java 中何时会抛出 IllegalStateException(未检查)?

javaobject oriented programmingprogramming更新于 2024/7/26 21:45:00

在 Java 中,IllegalStateException 是一种 未检查异常。如果我们在处理 java.util.package 集合框架,这种异常可能在我们的 Java 程序中出现。有许多集合,例如 List、Queue、Tree、Map,其中 ListQueues(Queue 和 Deque)在特定条件下会抛出此 IllegalStateException

何时会抛出 IllegalStateException

  • 当我们尝试在不适当的时间调用特定方法时,会抛出 IllegalStateException
  • 对于  java.util.List 集合,我们使用 ListIterator 接口的 next() 方法遍历 java.util.List。如果如果我们在调用 next()  方法之前调用 ListIterator  接口的 remove() 方法,则将抛出此异常,因为它将使 List  集合处于不稳定 状态
  • 如果我们想修改特定对象,我们将使用 ListIterator  接口的 set()  方法
  • 对于 队列,如果我们尝试将元素添加到 Queue,则必须确保队列未满。如果此队列已满,则我们无法添加该元素,这将导致抛出 IllegalStateExceptionexception 

示例

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)

相关文章