📚 Java 学习

10. 异常处理

让程序优雅地失败

什么是异常

程序运行时出的错误:数组越界、空指针、文件找不到、网络断了。Java 用异常对象来表示错误。

int[] arr = {1, 2, 3};
System.out.println(arr[10]);
// 运行时抛出 ArrayIndexOutOfBoundsException

try-catch-finally

try {
    // 可能出错的代码
    int result = 10 / 0;
} catch (ArithmeticException e) {
    // 出错了怎么办
    System.out.println("除数不能为零: " + e.getMessage());
} finally {
    // 无论对错都执行(通常清理资源)
    System.out.println("清理资源");
}

异常体系

throws 与 throw

// throws:方法声明可能抛出异常
public void readFile(String path) throws IOException {
    FileReader fr = new FileReader(path);  // 可能抛 IOException
}

// throw:手动抛出异常
public void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("年龄不能为负");
    }
    this.age = age;
}

自定义异常

public class BusinessException extends RuntimeException {
    private int code;
    public BusinessException(int code, String msg) {
        super(msg);
        this.code = code;
    }
    public int getCode() { return code; }
}

// 使用
throw new BusinessException(40401, "用户不存在");

try-with-resources

Java 7+ 自动关闭资源(实现 AutoCloseable 的对象),不用手动 finally close:

try (FileReader fr = new FileReader("file.txt");
     BufferedReader br = new BufferedReader(fr)) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}
// 自动关闭 fr 和 br,不用写 finally