Java 的异常机制是围绕 “抛出异常 — 捕获异常 — 处理或终止” 这一套流程设计的,核心目的是把“出错时的处理逻辑”和“正常业务逻辑”解耦。
下面从 整体流程 → 关键概念 → 执行顺序 → 常见误区 来讲。
当程序运行过程中出现“不符合预期的情况”时:
Exception / Error)try-catch 能捕获该异常catch 执行处理逻辑stack trace)Throwable
├── Error(严重错误,通常不应该捕获)
│ └── OutOfMemoryError
├── Exception
│ ├── RuntimeException(非受检异常)
│ │ └── NullPointerException
│ └── 其他Exception(受检异常)
│ └── IOException
分类要点:
Error:系统级问题,不处理RuntimeException:不需要显式声明| 关键字 | 作用 |
|---|---|
try |
监控可能出错的代码 |
catch |
捕获并处理异常 |
finally |
无论是否异常都会执行 |
throw |
手动抛出异常 |
throws |
方法声明可能抛出的异常 |
try {
System.out.println("try");
int x = 1 / 0;
} catch (ArithmeticException e) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
System.out.println("end");
输出:
try
catch
finally
end
✅ finally 总是执行(哪怕 return、throw 也一样)
❌ catch 只在异常类型匹配时执行
⚠️ try 中异常点之后的代码不会执行
void a() throws Exception {
b();
}
void b() throws Exception {
c();
}
void c() {
throw new Exception("error");
}
异常路径:
c() → b() → a() → JVM
try-catch)throws)throw vs throwsvoid test() throws IOException {
throw new IOException("file error");
}
throw:真正抛出异常对象throws:告诉调用者“我可能抛这个异常”try {
return 1;
} finally {
return 2; // 最终返回 2
}
⚠️ 不推荐在 finally 中 return
catch (Exception e) {
e.printStackTrace();
}
问题:
✅ 推荐:
❌ 错误用法:
try {
if (x == null) throw new Exception();
} catch (Exception e) {
...
}
✅ 应该用 if 判断,而不是异常
✅ 该捕获就捕获,不该吞就抛
✅ 自定义异常要继承 Exception 或 RuntimeException
✅ 异常信息要清晰、可读
✅ 资源使用 try-with-resources
try (InputStream in = new FileInputStream("a.txt")) {
...
}
如果你愿意,我可以:
你想深入哪一块?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。