“运行时异常”(Runtime Exception / Runtime Error)通常指程序在编译通过、但运行过程中出现的错误,比如空指针、数组越界、类型转换错误、除零、文件找不到、内存溢出等。
应对运行时异常,一般可以从 预防、捕获、排查、恢复 四个层面来做。
很多运行时异常是可以通过编码习惯避免的。
if (user != null && user.getName() != null) {
...
}
if (index >= 0 && index < list.size()) {
list.get(index);
}
if (age < 0) {
throw new IllegalArgumentException("age 不能为负");
}
捕获可预见的异常,避免程序崩溃。
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
log.error("除零异常", e);
}
确保资源释放(连接、文件、线程)。
try (InputStream in = new FileInputStream("a.txt")) {
...
} catch (IOException e) {
e.printStackTrace();
}
NullPointerException
at com.xxx.Service.getUser(Service.java:23)
→ 直接看“你自己的代码行号”
| 异常 | 原因 |
|---|---|
| NullPointerException | 调用了 null 对象 |
| IndexOutOfBounds | 下标越界 |
| ClassCastException | 类型转换错误 |
| IllegalArgumentException | 参数非法 |
| OutOfMemoryError | 内存泄漏 / 数据过大 |
| StackOverflowError | 无限递归 |
int value = safeParse(input, 0);
能预防的预防,能捕获的捕获,不能恢复的优雅失败。
如果你能告诉我:
我可以给你更针对性的解决方案。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。