Skip to content

Java 异常处理机制

TIP

异常处理是 Java 保证程序健壮性的重要机制,合理处理异常能让程序在出错时优雅地恢复或退出。

异常体系结构

Throwable
├── Error(不可恢复的错误)
│   ├── OutOfMemoryError
│   ├── StackOverflowError
│   └── NoClassDefFoundError
└── Exception(可处理的异常)
    ├── RuntimeException(运行时异常/非受检异常)
    │   ├── NullPointerException
    │   ├── ArrayIndexOutOfBoundsException
    │   ├── IllegalArgumentException
    │   └── ArithmeticException
    └── 非运行时异常(受检异常)
        ├── IOException
        ├── SQLException
        └── ClassNotFoundException

try-catch-finally

java
try {
    int result = 10 / 0;  // 会抛出 ArithmeticException
} catch (ArithmeticException e) {
    System.err.println("除数不能为0: " + e.getMessage());
} finally {
    System.out.println("无论是否异常都会执行");
}

try-with-resources(JDK7+)

自动关闭实现了 AutoCloseable 的资源:

java
try (FileInputStream fis = new FileInputStream("test.txt");
     BufferedReader br = new BufferedReader(new InputStreamReader(fis))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}
// 资源自动关闭,无需手动调用 close()

自定义异常

java
public class BusinessException extends RuntimeException {
    private Integer code;

    public BusinessException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }
}

// 使用
throw new BusinessException(400, "参数校验失败");

WARNING

  • 不要使用异常来控制正常流程
  • 尽量捕获具体的异常类型,避免 catch(Exception)
  • 在 finally 中释放资源,或使用 try-with-resources