跳转至

列出 5 个运行时异常

一、常见运行时异常

1. NullPointerException

最常见,访问 null 对象的方法/字段:

String s = null;
s.length();   // NullPointerException

2. IllegalArgumentException

参数不合法:

public void setAge(int age) {
    if (age < 0) throw new IllegalArgumentException("age 不能为负");
}

3. IllegalStateException

状态不对:

// 已经关闭的资源再用
scanner.close();
scanner.nextInt();   // IllegalStateException

4. IndexOutOfBoundsException

数组/集合越界:

int[] arr = new int[3];
arr[5];   // ArrayIndexOutOfBoundsException

List 是 IndexOutOfBoundsException

5. ClassCastException

类型转换错误:

Object o = "abc";
Integer i = (Integer) o;   // ClassCastException

6. ArithmeticException

算术错误:

int i = 1 / 0;   // ArithmeticException

7. ConcurrentModificationException

迭代时修改集合:

for (String s : list) {
    list.remove(s);   // ConcurrentModificationException
}

8. UnsupportedOperationException

不支持的操作:

Collections.unmodifiableList(new ArrayList<>()).add(1);

二、记忆口诀

NPE、IAE、ISE、IOOBE、CCE。

三、怎么避免

  • 判空(Optional)。
  • 参数校验(@NotNull)。
  • 用迭代器或 removeIf 删除。
  • 边界检查。

面试要求

题目只要 5 个,答出 NPE、IllegalArgumentException、IllegalStateException、IndexOutOfBoundsException、ClassCastException 即可。