好,这一题非常适合“一页背完 + 面试不慌” 👍
我按你要求,严格按「运行时 / 编译时」来分类,顺便把高频场景 + 记忆口诀都给你。
Java 常见异常
按「运行时异常 / 编译时异常」分类速查表
一句话总览:
- 运行时异常(RuntimeException):程序能跑,跑着跑着炸
- 编译时异常(Checked Exception):代码都不让你过
一、异常体系结构(先有全局观)
Throwable
├── Error (系统级错误,基本不管)
└── Exception
├── RuntimeException ← 运行时异常
└── 非 RuntimeException ← 编译时异常
二、运行时异常(RuntimeException)⭐ 高频重点
特点:
❌ 编译不强制处理
❌ 多数由逻辑错误引起
1️⃣ NullPointerException(空指针)
String s = null;
s.length(); // NPE
📌 场景:
- 对 null 调方法
- 拆箱(Integer → int)
2️⃣ ArrayIndexOutOfBoundsException(数组越界)
int[] arr = new int[3];
arr[3] = 10;
3️⃣ StringIndexOutOfBoundsException
"abc".charAt(3);
4️⃣ ClassCastException(类型转换异常)
Object o = "hello";
Integer i = (Integer) o;
5️⃣ ArithmeticException(算术异常)
int x = 10 / 0;
6️⃣ NumberFormatException
int n = Integer.parseInt("abc");
7️⃣ IllegalArgumentException
Thread.sleep(-1);
8️⃣ ConcurrentModificationException
for (String s : list) {
list.remove(s);
}
✅ 运行时异常速记口诀
空指针、越界、类型错、参数非法、算术炸
三、编译时异常(Checked Exception)⭐ 必须会
特点:
✅ 编译期强制处理(try/catch 或 throws)
✅ 多为 外部资源 / 不可控因素
1️⃣ IOException(I/O 异常之王)
FileInputStream fis = new FileInputStream("a.txt");
📌 子类:
- FileNotFoundException
- EOFException
2️⃣ SQLException(数据库)
Connection conn = DriverManager.getConnection(...);
3️⃣ ClassNotFoundException
Class.forName("com.mysql.Driver");
4️⃣ InterruptedException(线程)
Thread.sleep(1000);
5️⃣ ParseException(解析异常)
new SimpleDateFormat("yyyy-MM-dd").parse("2024/01/01");
✅ 编译时异常速记口诀
IO、SQL、反射、线程、解析
四、运行时 vs 编译时异常(对比总结)
| 对比点 | 运行时异常 | 编译时异常 |
|---|---|---|
| 是否强制处理 | ❌ | ✅ |
| 发生时机 | 运行期 | 编译期 |
| 原因 | 程序 bug | 外部环境 |
| 继承关系 | RuntimeException | Exception |
五、面试必问:为什么要区分?
为什么 Checked Exception 存在?
📌 标准回答:
因为有些异常程序员无法完全控制(如 IO、网络),
Java 强制开发者在编译期就考虑异常处理,提升系统健壮性。
六、最佳实践(很重要)
1️⃣ 业务异常 ≠ 系统异常
throw new IllegalStateException("用户状态非法");
2️⃣ 不要滥用 Exception
❌
catch (Exception e) {}
✅
catch (IOException e) {}
3️⃣ 运行时异常别 try 太多
修逻辑,比 try 更重要
七、一页终极记忆图(文字版)
运行时异常:
NPE / 越界 / 类型转换 / 算术 / 参数非法
编译时异常:
IO / SQL / 线程 / 反射 / 解析
八、下一步你可以继续深挖 👇
我可以帮你:
- 🔥 异常处理最佳实践(try-catch-finally)
- 🧠 自定义异常 + 全局异常设计
- 🧪 Spring 中异常是怎么统一处理的
- 📝 Java 异常面试 30 问速杀版
你是准备 面试突击,还是想往 工程实战 走?