IllegalStateException用于对象状态不合法时禁止方法调用,如未连接时发送数据、资源已关闭后继续使用、方法调用顺序错误或迭代中并发修改,语义清晰表明“当前状态不允许此操作”。

IllegalStateException 用于表示对象当前所处的状态不适合调用某个方法。当一个对象的方法在特定状态下不能被调用时,抛出此异常是合理且语义清晰的选择。它属于运行时异常(RuntimeException),不需要强制捕获或声明。
当对象未处于预期状态却尝试执行某操作时,应抛出 IllegalStateException。
示例:自定义连接类
<font face="Courier New,Courier,monospace">public class Connection {
private boolean connected = false;
public void connect() {
connected = true;
System.out.println("连接成功");
}
public void sendData(String data) {
if (!connected) {
throw new IllegalStateException("连接未建立,无法发送数据");
}
System.out.println("发送数据: " + data);
}
public static void main(String[] args) {
Connection conn = new Connection();
// conn.sendData("Hello"); // 抛出 IllegalStateException
conn.connect();
conn.sendData("Hello"); // 正常执行
}
}</font>当资源(如流、线程池、数据库连接)已经被关闭,再次使用时应阻止操作并提示非法状态。
立即学习“Java免费学习笔记(深入)”;
示例:线程池提交任务
<font face="Courier New,Courier,monospace">ExecutorService executor = Executors.newSingleThreadExecutor();
executor.shutdown();
// 再次提交任务会抛出 IllegalStateException
try {
executor.submit(() -> System.out.println("任务执行"));
} catch (IllegalStateException e) {
System.out.println("无法提交任务:线程池已关闭");
}</font>某些方法必须按特定顺序调用。如果调用顺序错误,可使用 IllegalStateException 提醒使用者。
示例:构建器模式中重复构建
<font face="Courier New,Courier,monospace">public class PersonBuilder {
private String name;
private int age;
private boolean built = false;
public PersonBuilder setName(String name) {
if (built) throw new IllegalStateException("Person 已构建完成,不可修改");
this.name = name;
return this;
}
public PersonBuilder setAge(int age) {
if (built) throw new IllegalStateException("Person 已构建完成,不可修改");
this.age = age;
return this;
}
public Person build() {
if (built) throw new IllegalStateException("Person 只能构建一次");
built = true;
return new Person(name, age);
}
}</font>Java 集合框架中的许多迭代器会在检测到并发修改时抛出 ConcurrentModificationException,它继承自 RuntimeException,但部分自定义集合可能直接使用 IllegalStateException 表达类似语义。
示例:手动实现迭代保护
<font face="Courier New,Courier,monospace">public class SimpleList<T> {
private List<T> data = new ArrayList<>();
private int modCount = 0;
public Iterator<T> iterator() {
int expected = modCount;
return new Iterator<T>() {
public boolean hasNext() {
checkModification();
return ...;
}
public T next() {
checkModification();
...
}
private void checkModification() {
if (modCount != expected) {
throw new IllegalStateException("列表在迭代过程中被修改");
}
}
};
}</font>IllegalStateException 的核心在于“状态非法”,而不是参数错误(那是 IllegalArgumentException 的职责)。它帮助开发者更早发现逻辑错误,提升代码的健壮性和可维护性。
基本上就这些场景最常见。用好这个异常,能让调用者清楚知道“不是不能做,而是现在不能做”。
以上就是Java中IllegalStateException使用场景及示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号