java如何处理异常
异常处理的基本概念
Java中的异常处理通过try-catch-finally机制实现,用于捕获和处理程序运行时可能出现的错误或异常情况。异常分为检查型异常(如IOException)和非检查型异常(如NullPointerException)。
使用 try-catch 块
通过try块包裹可能抛出异常的代码,catch块捕获并处理特定类型的异常:
try {
int result = 10 / 0; // 抛出 ArithmeticException
} catch (ArithmeticException e) {
System.out.println("除零错误: " + e.getMessage());
}
多个catch块可以处理不同类型的异常,需按从具体到通用的顺序排列。
finally 块
无论是否发生异常,finally块中的代码都会执行,通常用于释放资源(如关闭文件流):

try {
FileReader file = new FileReader("test.txt");
} catch (IOException e) {
System.out.println("文件读取错误");
} finally {
System.out.println("资源清理完成");
}
抛出异常
通过throw主动抛出异常对象:
if (input < 0) {
throw new IllegalArgumentException("输入不能为负数");
}
声明异常
方法签名中使用throws声明可能抛出的检查型异常,调用者需处理或继续抛出:

public void readFile() throws IOException {
FileReader file = new FileReader("test.txt");
}
自定义异常
继承Exception或RuntimeException创建自定义异常类:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
try-with-resources
自动管理资源(实现AutoCloseable接口的类),无需显式调用close():
try (FileReader file = new FileReader("test.txt")) {
// 使用资源
} catch (IOException e) {
System.out.println("IO异常");
}
异常链
通过构造方法或initCause()将底层异常包装为高层异常,保留原始异常信息:
try {
// 代码逻辑
} catch (LowLevelException e) {
throw new HighLevelException("高层异常", e);
}
最佳实践
- 避免捕获过于通用的异常(如直接捕获
Exception)。 - 优先使用非检查型异常处理编程错误(如
NullPointerException)。 - 在日志中记录异常的堆栈轨迹(
e.printStackTrace()或日志框架)。 - 确保资源释放,优先使用
try-with-resources。






