精通 Java 异常处理:try-catch-finally 与资源管理
精通 Java 异常处理
探索 Java try-catch-finally 机制与 try-with-resources 如何助你编写健壮、无错误代码。
try…catch 结构是 Java 优雅错误处理的核心。它允许程序预判运行时问题并响应而不崩溃。
规范语法:
try { // 可能抛异常的代码 } catch (ExceptionType e) { // 处理异常 }
try 块包含可能抛出异常的代码。异常发生时控制权跳转到匹配的 catch 块,可做适当反应。
示例:处理 ArithmeticException
class Main { public static void main(String[] args) { try { int result = 5 / 0; System.out.println("This line is never reached."); } catch (ArithmeticException e) { System.out.println("Caught: " + e.getMessage()); } } }
输出
Caught: / by zero
除零触发 ArithmeticException。catch 块捕获它,防止程序崩溃。
提示:若只关心确保 finally 运行,可省略 catch 块,但 catch 不能脱离 try 存在。
使用 finally 块
finally 子句保证无论是否抛出异常都执行:
class Main { public static void main(String[] args) { try { int result = 5 / 0; } finally { System.out.println("Cleanup actions run here."); } } }
输出
Cleanup actions run here. Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:4)
finally 块在 try 后执行,即使异常打断正常流程。
组合 Try、Catch 与 Finally
最健壮的代码使用三个子句处理错误、上报并清理资源。文件处理示例:
import java.io.*; class ListOfNumbers { private int[] list = {5, 6, 8, 9, 2}; public void writeList() { PrintWriter out = null; try { System.out.println("Attempting to write to file."); out = new PrintWriter(new FileWriter("OutputFile.txt")); for (int i = 0; i < 7; i++) { out.println("Value at: " + i + " = " + list[i]); } } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not opened."); } } } } class Main { public static void main(String[] args) { new ListOfNumbers().writeList(); } }
输出
Attempting to write to file. Exception: Index 5 out of bounds for length 5 Closing PrintWriter
数组越界触发异常,被捕获上报。finally 块确保 PrintWriter 关闭,防止资源泄漏。
最佳实践:始终将清理逻辑(关闭文件、套接字、数据库连接)置于 finally 块。
注意:finally 可能不运行:JVM 退出(如 System.exit())、finally 内抛异常、线程突发终止。
处理多种异常类型
单个 try 可跟多个 catch 子句,各针对特定异常:
class ListOfNumbers { private int[] arr = new int[10]; public void writeList() { try { arr[10] = 11; } catch (NumberFormatException e) { System.out.println("NumberFormatException: " + e.getMessage()); } catch (IndexOutOfBoundsException e) { System.out.println("IndexOutOfBoundsException: " + e.getMessage()); } } } class Main { public static void main(String[] args) { new ListOfNumbers().writeList(); } }
输出
IndexOutOfBoundsException: Index 10 out of bounds for length 10
运行时依次尝试第一个 catch;不匹配则继续下一个直到匹配。
单个 catch 捕获多异常(Java 7+)
Java 7 引入在单个 catch 合并异常类型,减少重复:
try { // 风险代码 } catch (IOException | SQLException ex) { // 统一处理 }
当不同异常可同等处理时使用此特性。
Try-With-Resources 自动清理
try-with-resources 语句自动关闭实现 AutoCloseable 的资源:
try (PrintWriter out = new PrintWriter(new FileWriter("OutputFile.txt"))) { // 使用资源 } catch (IOException e) { // 处理 I/O 错误 }
资源声明在括号内,块退出时自动关闭,即使发生异常。
深入见解请探索官方 Java 文档 try-with-resources。
java
- 精通 Java 运算符:类型、语法与实战示例
- Java 注释:类型、用法与最佳实践
- 精通 Java 增强 for 循环:语法、示例与最佳实践
- 精通 Java 字符串:创建、方法与最佳实践
- 精通 Java 接口:概念、实现与最佳实践
- 精通 Java 匿名内部类:定义、语法与实战示例
- 精通 Java 异常处理:try-catch、finally、throw 与 throws 详解
- 精通 Java 多异常捕获:单 catch 块处理多异常
- 精通 Java Try-With-Resources:自动资源管理详解
- Java 注解详解:类型、放置位置与实战示例
- Java 断言实战指南:尽早发现 Bug 与保障代码可靠性
- 深入理解 Java Vector:用法、特性及与 ArrayList 的对比