Java try-catch异常捕获 #

一、try-catch基本语法 #

1.1 基本结构 #

java
try {
    // 可能抛出异常的代码
} catch (异常类型 变量名) {
    // 异常处理代码
}

1.2 使用示例 #

java
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("除零错误: " + e.getMessage());
}

二、多重catch #

2.1 多个catch块 #

java
try {
    int[] arr = new int[5];
    arr[10] = 100;
    int result = 10 / 0;
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("数组越界");
} catch (ArithmeticException e) {
    System.out.println("算术错误");
}

2.2 catch顺序 #

子类异常必须在父类异常之前。

java
try {
    // ...
} catch (FileNotFoundException e) {  // 子类
    System.out.println("文件未找到");
} catch (IOException e) {  // 父类
    System.out.println("IO错误");
}

// 错误:父类在前
// try {
//     // ...
// } catch (IOException e) {  // 父类
// } catch (FileNotFoundException e) {  // 子类:永远不会执行
// }

2.3 多异常捕获(Java 7+) #

java
try {
    // ...
} catch (FileNotFoundException | IOException e) {
    System.out.println("文件操作错误: " + e.getMessage());
}

三、finally块 #

3.1 基本用法 #

java
try {
    // 可能抛出异常的代码
} catch (Exception e) {
    // 异常处理
} finally {
    // 无论是否异常都执行
}

3.2 使用示例 #

java
FileInputStream fis = null;
try {
    fis = new FileInputStream("test.txt");
    // 读取文件
} catch (FileNotFoundException e) {
    System.out.println("文件未找到");
} finally {
    if (fis != null) {
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3.3 finally特点 #

java
public int test() {
    try {
        return 1;
    } finally {
        System.out.println("finally执行");  // 会执行
    }
}

// finally在return之前执行

3.4 finally不执行的情况 #

java
try {
    System.exit(0);  // 退出JVM
} finally {
    System.out.println("不会执行");
}

四、try-with-resources #

4.1 语法(Java 7+) #

java
try (资源声明) {
    // 使用资源
} catch (Exception e) {
    // 异常处理
}

4.2 使用示例 #

java
// 自动关闭资源
try (FileInputStream fis = new FileInputStream("test.txt")) {
    // 读取文件
} catch (IOException e) {
    e.printStackTrace();
}
// fis自动关闭

// 多个资源
try (FileInputStream fis = new FileInputStream("in.txt");
     FileOutputStream fos = new FileOutputStream("out.txt")) {
    // 复制文件
} catch (IOException e) {
    e.printStackTrace();
}

五、异常信息获取 #

5.1 常用方法 #

java
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println(e.getMessage());        // / by zero
    System.out.println(e.toString());          // java.lang.ArithmeticException: / by zero
    e.printStackTrace();                       // 打印堆栈跟踪
}

5.2 获取详细堆栈 #

java
try {
    // ...
} catch (Exception e) {
    StackTraceElement[] stack = e.getStackTrace();
    for (StackTraceElement element : stack) {
        System.out.println(element.getClassName() + "." + 
                          element.getMethodName() + 
                          "(" + element.getLineNumber() + ")");
    }
}

六、异常链 #

6.1 保留原始异常 #

java
public void method1() throws Exception {
    try {
        method2();
    } catch (IOException e) {
        throw new Exception("操作失败", e);  // 保留原始异常
    }
}

public void method2() throws IOException {
    throw new IOException("文件读取错误");
}

6.2 获取原始异常 #

java
try {
    method1();
} catch (Exception e) {
    System.out.println(e.getMessage());       // 操作失败
    System.out.println(e.getCause());         // 原始异常
    e.getCause().printStackTrace();           // 原始异常堆栈
}

七、最佳实践 #

7.1 不要捕获后不处理 #

java
// 不推荐:空catch块
try {
    // ...
} catch (Exception e) {
    // 什么都不做
}

// 推荐:至少记录日志
try {
    // ...
} catch (Exception e) {
    e.printStackTrace();
    // 或使用日志框架
    // logger.error("错误", e);
}

7.2 使用具体异常类型 #

java
// 不推荐
try {
    // ...
} catch (Exception e) {  // 太宽泛
}

// 推荐
try {
    // ...
} catch (FileNotFoundException e) {
    // 文件不存在
} catch (IOException e) {
    // IO错误
}

7.3 资源释放 #

java
// 推荐:使用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) {
    e.printStackTrace();
}

八、总结 #

结构 说明
try 包含可能抛出异常的代码
catch 捕获并处理异常
finally 无论是否异常都执行
try-with-resources 自动关闭资源

try-catch要点:

  • catch顺序:子类在前,父类在后
  • finally总会执行(除非System.exit)
  • 使用try-with-resources自动关闭资源
  • 不要使用空catch块
最后更新:2026-03-26