java语言如何进行异常处理
Java 异常处理的基本结构
Java 通过 try-catch-finally 块实现异常处理。try 块包含可能抛出异常的代码,catch 块捕获并处理异常,finally 块用于执行必须运行的清理代码(无论是否发生异常)。
try {
// 可能抛出异常的代码
int result = 10 / 0; // 抛出 ArithmeticException
} catch (ArithmeticException e) {
// 处理算术异常
System.out.println("除数不能为零: " + e.getMessage());
} finally {
// 清理资源(如关闭文件、数据库连接)
System.out.println("finally 块始终执行");
}
捕获多个异常
可以定义多个 catch 块处理不同类型的异常,异常类型需从子类到父类排列。
try {
int[] arr = {1, 2};
System.out.println(arr[3]); // 抛出 ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界: " + e.getMessage());
} catch (Exception e) {
System.out.println("通用异常处理: " + e.getMessage());
}
使用 throws 声明异常
若方法内部不处理异常,可通过 throws 将异常抛给调用者处理。
public void readFile() throws IOException {
FileReader file = new FileReader("test.txt"); // 可能抛出 IOException
}
自定义异常
通过继承 Exception 或 RuntimeException 创建自定义异常类。
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 使用自定义异常
try {
throw new CustomException("自定义异常示例");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
异常链与重新抛出异常
通过 throw 重新抛出异常,或使用异常链保留原始异常信息。

try {
// 代码逻辑
} catch (IOException e) {
throw new RuntimeException("高阶异常", e); // 传递原始异常
}
Java 7 增强的异常处理
- 多重捕获:一个
catch块处理多种异常类型。 - try-with-resources:自动关闭资源(如
InputStream),资源需实现AutoCloseable接口。
// 多重捕获
try {
// 代码逻辑
} catch (IOException | SQLException e) {
System.out.println("IO 或 SQL 异常: " + e.getMessage());
}
// try-with-resources
try (FileInputStream fis = new FileInputStream("file.txt")) {
// 自动关闭 fis
} catch (IOException e) {
e.printStackTrace();
}
注意事项
- 避免空的
catch块,需至少记录异常信息。 - 区分受检异常(
Exception子类,必须处理)和非受检异常(RuntimeException子类,可选择性处理)。 finally块中避免返回语句,否则会覆盖try或catch的返回值。






