Skip to content

Try Catch

try-catch 是 Java 处理异常最直接的方式。但这里面有几个坑,新手容易踩,老手偶尔也会翻车。

基本结构

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

基本用法

java
public class TryCatchBasicDemo {

    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("算术异常: " + e.getMessage());
        } finally {
            System.out.println("finally 执行");
        }
    }
}

多 catch

java
public class MultiCatchDemo {

    public static void main(String[] args) {
        try {
            String s = null;
            s.length();  // NullPointerException
        } catch (NullPointerException e) {
            System.out.println("空指针异常");
        } catch (Exception e) {
            System.out.println("其他异常");
        }
    }
}

JDK 7+ 多异常合并

java
public class MultiCatchJDK7Demo {

    public static void main(String[] args) {
        try {
            int[] arr = {1, 2, 3};
            // arr[5] = 10;  // ArrayIndexOutOfBoundsException
            throw new IOException("IO 错误");
        } catch (ArrayIndexOutOfBoundsException | IOException e) {
            // JDK 7+ 可以合并处理
            System.out.println("异常: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("其他异常");
        }
    }
}

finally 中的 return

这是个容易翻车的细节:

java
public class FinallyReturnDemo {

    public static void main(String[] args) {
        System.out.println(test());  // 输出 2,不是 1
    }

    static int test() {
        try {
            return 1;
        } finally {
            return 2;  // finally 中的 return 会覆盖 try 中的
        }
    }
}

永远不要在 finally 中写 return。这会让 try 中的异常被吞掉,排查问题时会让你怀疑人生。

避坑指南

异常匹配遵循「子类在前、父类在后」的原则。如果反过来写,编译器会直接报错或跳过子类 catch。

finally 总会执行,即使 try 或 catch 中有 return。只有两种情况例外:System.exit() 终止 JVM,或者 fatal error 导致线程崩溃。

基于 VitePress 构建