java 如何处理异常
异常处理的基本概念
在 Java 中,异常是程序运行时发生的意外事件,可能破坏正常流程。Java 通过 try-catch、throw、throws 和 finally 等机制处理异常,确保程序健壮性。
使用 try-catch 块
try-catch 是处理异常的核心结构。将可能抛出异常的代码放在 try 块中,异常捕获逻辑放在 catch 块中。
try {
int result = 10 / 0; // 抛出 ArithmeticException
} catch (ArithmeticException e) {
System.out.println("除零错误: " + e.getMessage());
}
多重 catch 块
可以捕获多种异常,按顺序匹配。需注意子类异常应排在父类之前。
try {
int[] arr = new int[5];
arr[10] = 1; // 抛出 ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界: " + e.getMessage());
} catch (Exception e) {
System.out.println("通用异常: " + e.getMessage());
}
finally 块
无论是否发生异常,finally 块中的代码都会执行,常用于资源清理(如关闭文件流)。
try {
FileInputStream file = new FileInputStream("test.txt");
} catch (IOException e) {
System.out.println("文件读取错误: " + e.getMessage());
} finally {
System.out.println("资源清理完成");
}
throw 关键字
主动抛出异常,通常用于自定义异常逻辑。
void validateAge(int age) {
if (age < 18) {
throw new ArithmeticException("年龄不足");
}
}
throws 关键字
在方法声明中指定可能抛出的异常,强制调用者处理。
void readFile() throws IOException {
FileInputStream file = new FileInputStream("test.txt");
}
自定义异常
通过继承 Exception 或 RuntimeException 创建自定义异常类。

class CustomException extends Exception {
CustomException(String message) {
super(message);
}
}
void checkValue(int value) throws CustomException {
if (value < 0) {
throw new CustomException("值不能为负数");
}
}
异常处理的最佳实践
- 避免空的
catch块,至少记录日志。 - 优先捕获具体异常,而非通用
Exception。 - 使用
try-with-resources自动管理资源(Java 7+)。 - 在业务逻辑中合理使用受检异常(Checked Exception)和非受检异常(Unchecked Exception)。
// try-with-resources 示例
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("IO错误: " + e.getMessage());
}
通过以上方法,可以有效处理 Java 中的异常,提升代码的可靠性和可维护性。






