java中如何处理异常
异常处理的基本结构
在Java中,异常处理主要通过 try-catch-finally 块实现。
try {
// 可能抛出异常的代码
} catch (ExceptionType1 e1) {
// 处理 ExceptionType1 类型的异常
} catch (ExceptionType2 e2) {
// 处理 ExceptionType2 类型的异常
} finally {
// 无论是否发生异常都会执行的代码(可选)
}
捕获特定异常
明确捕获具体异常类型,避免笼统使用 Exception。
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("除零错误: " + e.getMessage());
}
多重异常捕获
从Java 7开始,可以在一个 catch 块中捕获多种异常。
try {
// 可能抛出 IOException 或 SQLException 的代码
} catch (IOException | SQLException e) {
System.out.println("IO或数据库错误: " + e.getMessage());
}
使用 finally 释放资源
finally 块通常用于关闭文件、数据库连接等资源。
FileInputStream file = null;
try {
file = new FileInputStream("test.txt");
// 读取文件
} catch (IOException e) {
System.out.println("文件读取错误");
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
System.out.println("关闭文件失败");
}
}
}
try-with-resources 语法
Java 7引入的自动资源管理语法,适用于实现 AutoCloseable 接口的资源。
try (FileInputStream file = new FileInputStream("test.txt")) {
// 自动关闭文件流
} catch (IOException e) {
System.out.println("文件操作异常");
}
抛出异常
通过 throw 主动抛出异常,通常用于自定义逻辑验证。
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负数");
}
自定义异常
继承 Exception 或 RuntimeException 创建自定义异常类。
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 使用示例
try {
throw new CustomException("自定义异常");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
异常链
通过 initCause() 或构造方法传递原始异常,保留完整的异常信息。

try {
// 某些操作
} catch (IOException e) {
throw new CustomException("操作失败").initCause(e);
}
最佳实践
- 避免捕获异常后忽略(如空
catch块)。 - 优先使用具体的异常类型而非通用
Exception。 - 在日志中记录异常堆栈(
e.printStackTrace()或日志框架)。 - 资源操作优先使用
try-with-resources。






