Skip to main content
Version: Next

异常处理

程序运行中难免出错(文件不存在、网络中断、空指针……)。Java 用异常机制把"正常逻辑"和"错误处理"分离。

异常体系​

Throwable
├── Error 严重错误(如 OOM),程序无法处理
└── Exception
├── RuntimeException 运行时异常(unchecked),编译不强制处理
└── 其他 Exception 受检异常(checked),编译器强制处理

常见运行时异常:NullPointerException、ArrayIndexOutOfBoundsException、ClassCastException、IllegalArgumentException。

try-catch-finally​

try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("除数不能为 0:" + e.getMessage());
} finally {
System.out.println("无论是否异常都会执行,常用于释放资源");
}

可以捕获多种异常:

try {
// ...
} catch (NumberFormatException | NullPointerException e) {
// 多种异常同样处理
} catch (Exception e) {
// 兜底:父类 catch 必须放在子类之后
}

throws 与 throw​

// throw:主动抛出一个异常对象
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负");
}
}

// throws:声明方法可能抛出受检异常,交给调用者处理
public String readFile(String path) throws IOException {
return Files.readString(Path.of(path));
}

自定义异常​

public class AgeInvalidException extends RuntimeException {
public AgeInvalidException(String message) {
super(message);
}
}

// 使用
if (age < 0 || age > 150) {
throw new AgeInvalidException("非法年龄:" + age);
}

最佳实践​

  • 不要用异常控制正常流程,异常只处理"意外"。
  • 不要捕获后什么都不做(吞异常),至少要打印日志。
  • 资源释放优先用 try-with-resources:
try (Scanner sc = new Scanner(System.in)) {
// 使用完毕后自动关闭,无需手动 close
}