java 如何处理异常
异常处理的基本概念
在Java中,异常是程序运行时可能发生的错误或意外情况。异常处理机制允许程序在出现问题时继续执行或优雅地终止,而不是直接崩溃。
使用 try-catch 块
try-catch 是处理异常的基本结构。将可能抛出异常的代码放在 try 块中,并在 catch 块中捕获并处理异常。
try {
// 可能抛出异常的代码
int result = 10 / 0; // 抛出 ArithmeticException
} catch (ArithmeticException e) {
// 处理异常
System.out.println("除数不能为零");
}
多个 catch 块
可以针对不同类型的异常分别处理。

try {
// 可能抛出多种异常的代码
int[] arr = new int[5];
arr[10] = 5; // 抛出 ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界");
} catch (Exception e) {
System.out.println("其他异常");
}
finally 块
无论是否发生异常,finally 块中的代码都会执行,通常用于释放资源(如关闭文件或数据库连接)。
try {
// 可能抛出异常的代码
FileInputStream file = new FileInputStream("test.txt");
} catch (FileNotFoundException e) {
System.out.println("文件未找到");
} finally {
System.out.println("资源清理完成");
}
throws 关键字
如果方法内部不处理异常,可以通过 throws 声明将异常抛给调用者处理。

public void readFile() throws FileNotFoundException {
FileInputStream file = new FileInputStream("test.txt");
}
自定义异常
可以通过继承 Exception 或 RuntimeException 创建自定义异常类。
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 使用自定义异常
try {
throw new CustomException("自定义异常示例");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
异常链
可以通过 initCause() 或构造函数传递异常的根本原因。
try {
// 模拟异常链
NullPointerException npe = new NullPointerException();
throw new RuntimeException("外层异常", npe);
} catch (RuntimeException e) {
System.out.println("捕获异常: " + e.getCause());
}
最佳实践
- 避免捕获过于宽泛的异常(如直接捕获
Exception),应尽可能捕获具体异常。 - 在
finally块中释放资源,确保资源不会泄漏。 - 自定义异常应提供有意义的错误信息,便于调试。
- 日志记录异常信息,便于后续排查问题。






