现代错误处理

错误处理是软件工程中最重要却最常被忽视的环节。C++ 经历了从返回码到异常,再到类型安全的 std::expected 的演进。本章帮助你理解每种策略的优劣,并根据场景做出正确选择。

错误处理的演进

C 风格:返回码与 errno

最原始的错误处理方式——函数返回一个整数表示成功或失败:

// C 风格错误处理
int read_file(const char* path, char* buffer, size_t size) {
    FILE* f = fopen(path, "r");
    if (!f) return -1;  // 错误码 -1

    size_t n = fread(buffer, 1, size, f);
    if (ferror(f)) {
        fclose(f);
        return -2;  // 不同的错误码
    }
    fclose(f);
    return 0;  // 成功
}

// 调用方——很容易忘记检查返回值!
char buf[1024];
read_file("data.txt", buf, sizeof(buf));  // 返回值被忽略了
process(buf);  // 可能在处理垃圾数据

C 风格错误码的致命缺陷:编译器不会强制调用方检查返回值。调查显示,大量的 C 代码 bug 源于忽略了函数的错误返回值。errno 更糟——它是全局变量,多线程下不安全且极易被覆盖。

C++ 异常:throw/catch

异常解决了"错误可被忽略"的问题——如果不处理,程序会终止:

// 异常风格
std::string read_file(const std::string& path) {
    std::ifstream f(path);
    if (!f) throw std::runtime_error("无法打开文件: " + path);

    std::string content((std::istreambuf_iterator<char>(f)),
                         std::istreambuf_iterator<char>());
    return content;
}

// 调用方——不可能忽略错误
try {
    auto data = read_file("data.txt");
    process(data);
} catch (const std::runtime_error& e) {
    std::cerr << "错误: " << e.what() << '\n';
}

但异常引入了新的问题:

  • 隐式控制流:看不出哪一行可能抛异常,代码推理变困难
  • 性能开销:异常抛出时的栈展开代价很高(happy path 几乎无开销)
  • 二进制膨胀:异常处理表增加可执行文件体积
  • 不适合高频失败:如果"失败"是正常业务路径(如解析用户输入),异常太重了

现代 C++:显式、可组合的错误处理

现代 C++ 提供了类型安全的错误处理工具:

  • std::optional<T> (C++17)——"可能没有值",适合不需要错误详情的场景
  • std::expected<T, E> (C++23)——"要么有值,要么有错误",类似 Rust 的 Result<T, E>

这两者的共同优势:错误在类型签名中可见,编译器和开发者都能明确知道函数可能失败。

std::expected<T, E> (C++23)

std::expected<T, E> 表达的语义是:"Either a value OR an error"——函数成功时持有类型为 T 的值,失败时持有类型为 E 的错误信息。

基本用法

#include <expected>
#include <string>
#include <charconv>

// 返回 expected: 成功时是 int,失败时是 string 描述错误原因
std::expected<int, std::string> parse_int(std::string_view str) {
    int result{};
    auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result);

    if (ec == std::errc::invalid_argument) {
        return std::unexpected("不是有效数字: " + std::string(str));
    }
    if (ec == std::errc::result_out_of_range) {
        return std::unexpected("数值超出范围: " + std::string(str));
    }
    if (ptr != str.data() + str.size()) {
        return std::unexpected("存在非数字字符: " + std::string(str));
    }

    return result;  // 成功,直接返回值
}

注意语法差异:成功时直接 return value;,失败时需要 return std::unexpected(error);。这种不对称设计让成功路径更简洁(因为成功是常见路径)。

检查与访问

auto result = parse_int("42");

// 方式 1:布尔检查
if (result) {
    std::println("解析成功: {}", result.value());
} else {
    std::println("解析失败: {}", result.error());
}

// 方式 2:has_value()
if (result.has_value()) {
    std::println("值 = {}", *result);  // operator* 也可以访问值
}

// 方式 3:value_or 提供默认值
int val = result.value_or(0);  // 失败时返回 0

与异常的对比

// === 异常版本 ===
int parse_int_exc(std::string_view str) {
    // std::stoi 会在失败时抛出异常
    return std::stoi(std::string(str));
}

void process_input_exc(std::string_view input) {
    try {
        int age = parse_int_exc(input);
        if (age < 0 || age > 150)
            throw std::out_of_range("年龄不合理");
        register_user(age);
    } catch (const std::invalid_argument&) {
        show_error("请输入数字");
    } catch (const std::out_of_range&) {
        show_error("数值超出范围");
    }
}

// === expected 版本 ===
std::expected<int, std::string> parse_age(std::string_view input) {
    auto num = parse_int(input);
    if (!num) return num;  // 传播错误

    if (*num < 0 || *num > 150)
        return std::unexpected("年龄不合理: " + std::to_string(*num));

    return *num;
}

void process_input_exp(std::string_view input) {
    auto age = parse_age(input);
    if (age) {
        register_user(*age);
    } else {
        show_error(age.error());
    }
    // 控制流完全显式——每一步是否失败都清清楚楚
}

std::expected 的 Monadic 操作

C++23 为 std::expected 提供了三个"链式操作"方法,让你无需反复 if (!result) 就能构建错误处理管道:

and_then(f) —— 链式调用可能失败的操作

f 接收成功值,返回一个新的 expected。如果当前 expected 已经是错误状态,f 不会被调用。

std::expected<int, std::string> parse_int(std::string_view s);
std::expected<int, std::string> validate_positive(int n);
std::expected<User, std::string> find_user(int id);

// 链式调用——任意一步失败,后续步骤自动跳过
auto result = parse_int(input)
    .and_then(validate_positive)   // 验证是正数
    .and_then(find_user);          // 根据 ID 查找用户

if (result) {
    greet(*result);
} else {
    log_error(result.error());  // 拿到第一个失败步骤的错误信息
}

transform(f) —— 转换成功值

f 接收成功值,返回一个普通值(不是 expected)。结果自动包装进新的 expected。

// transform: 对成功值做变换,不会引入新的失败可能
auto name = parse_int(input)
    .and_then(find_user)
    .transform([](const User& u) { return u.name; });
// name 的类型: std::expected<std::string, std::string>

or_else(f) —— 处理/恢复错误

f 接收错误值,返回一个新的 expected(可以恢复为成功,或转换为不同的错误)。

// or_else: 尝试从错误中恢复
auto config = load_config_from_file("app.toml")
    .or_else([](const std::string& err) -> std::expected<Config, std::string> {
        std::println("配置文件加载失败({}), 使用默认配置", err);
        return Config::default_config();  // 恢复为成功
    });

构建错误处理管道

// 完整管道示例:解析 → 验证 → 转换 → 错误恢复
auto process_age_input(std::string_view input)
    -> std::expected<std::string, std::string>
{
    return parse_int(input)
        .and_then([](int n) -> std::expected<int, std::string> {
            if (n < 0 || n > 150)
                return std::unexpected("年龄超出合理范围");
            return n;
        })
        .transform([](int age) {
            if (age < 18) return std::string("未成年");
            if (age < 65) return std::string("成年");
            return std::string("老年");
        })
        .or_else([](const std::string& err) -> std::expected<std::string, std::string> {
            // 记录日志但仍返回错误
            log_warning("输入处理失败: " + err);
            return std::unexpected(err);
        });
}

记忆口诀:and_then = "如果成功,继续做(可能失败)";transform = "如果成功,转换一下(不会失败)";or_else = "如果失败,试着恢复"。这与 std::optional 的 monadic 操作完全一致。

何时使用异常

异常并没有被 std::expected 淘汰——它们各有适用场景:

适合使用异常的场景

  • 真正的意外情况:内存耗尽、磁盘已满、数据结构损坏——这些不属于正常业务逻辑
  • 构造函数失败:构造函数没有返回值,无法使用 expected
  • 跨越库边界:库可能不知道调用方如何处理错误,异常让选择权留给调用方
  • 深层嵌套调用:错误需要跨越多层函数栈传播时,逐层传递 expected 很繁琐
// 构造函数——只能用异常报告错误
class DatabaseConnection {
public:
    DatabaseConnection(const std::string& conn_str) {
        handle_ = db_connect(conn_str.c_str());
        if (!handle_) {
            throw std::runtime_error("数据库连接失败: " + conn_str);
        }
    }
    // ...
};

// 工厂函数——可以用 expected 替代异常
std::expected<DatabaseConnection, DbError> connect(const std::string& conn_str);

实践指导原则

经验法则:

  • 异常:用于 bug 和罕见的异常情况(程序员的错误、环境崩溃)
  • expected:用于领域错误——那些属于正常业务逻辑一部分的失败(用户输入无效、文件不存在、网络超时)
  • optional:用于"可能没有值"但不需要知道为什么没有的场景

noexcept

含义与用途

noexcept 声明一个函数承诺绝不抛出异常。如果函数内部确实抛出了异常,程序直接调用 std::terminate() 终止——没有栈展开,没有 catch。

// 声明不会抛出异常
void swap(Widget& a, Widget& b) noexcept {
    auto tmp = std::move(a);
    a = std::move(b);
    b = std::move(tmp);
}

// 析构函数隐式 noexcept(除非你显式声明 noexcept(false))
class Resource {
    ~Resource() {  // 隐式 noexcept
        cleanup();  // cleanup 绝对不能抛异常!
    }
};

必须标记 noexcept 的地方

  • 移动构造函数 / 移动赋值:std::vector 在重分配时,只有移动操作是 noexcept 的才会选择移动(否则回退到拷贝以保证强异常安全)
  • swap 函数:标准库的算法假设 swap 不抛异常
  • 析构函数:已经隐式 noexcept,显式标注也可以
class Buffer {
    std::unique_ptr<char[]> data_;
    size_t size_;
public:
    // 移动构造——必须 noexcept!
    Buffer(Buffer&& other) noexcept
        : data_(std::move(other.data_))
        , size_(std::exchange(other.size_, 0))
    {}

    // 移动赋值——必须 noexcept!
    Buffer& operator=(Buffer&& other) noexcept {
        data_ = std::move(other.data_);
        size_ = std::exchange(other.size_, 0);
        return *this;
    }
};

重要:如果你的移动构造函数不是 noexcept,std::vector 在扩容时会拷贝而非移动你的对象。这可能导致巨大的性能差异——一个 noexcept 关键字可能就是 O(n) 和 O(n*copy_cost) 的区别。

条件 noexcept

noexcept(expr) 可以根据编译期条件决定是否是 noexcept:

template<typename T>
class Wrapper {
    T value_;
public:
    // 只有当 T 的移动构造是 noexcept 时,Wrapper 的移动构造才是 noexcept
    Wrapper(Wrapper&& other) noexcept(std::is_nothrow_move_constructible_v<T>)
        : value_(std::move(other.value_))
    {}

    // noexcept(noexcept(...)) 模式——直接继承被调用表达式的 noexcept 性质
    void swap(Wrapper& other) noexcept(noexcept(std::swap(value_, other.value_))) {
        std::swap(value_, other.value_);
    }
};

错误策略对比

策略 错误信息 可忽略? 性能(失败路径) 适用场景
返回码 (int) 仅整数码 容易忽略 极快 C API、极度性能敏感
异常 (throw) 丰富(what()) 不可忽略 极慢(栈展开) 真正异常情况、构造函数
std::optional 无 需检查 快 "可能没有"即可,无需原因
std::expected 自定义 E 需检查 快 领域错误、需要错误详情

选择指南

  • 函数经常失败(如解析用户输入)→ std::expected
  • 失败不需要原因(如查找容器中的元素)→ std::optional
  • 失败是程序员的错误(前置条件违反)→ assert / std::terminate
  • 失败是罕见的异常情况(内存耗尽、文件系统损坏)→ 异常
  • 需要跨越多层传播且失败极其罕见 → 异常
  • 与 C 代码互操作 → 返回码

团队约定很重要:在一个项目中混用多种错误策略是正常的,但应该有明确的团队规范——哪些层用异常,哪些层用 expected。不一致的错误处理风格比使用"次优"策略更危险。

实际模式

完整示例:文件加载管道

#include <expected>
#include <fstream>
#include <string>
#include <sstream>
#include <print>

// 自定义错误类型
enum class FileError {
    not_found,
    permission_denied,
    parse_failed,
    invalid_format
};

std::string to_string(FileError e) {
    switch (e) {
        case FileError::not_found:        return "文件未找到";
        case FileError::permission_denied: return "权限不足";
        case FileError::parse_failed:     return "解析失败";
        case FileError::invalid_format:   return "格式无效";
    }
    return "未知错误";
}

// 步骤 1:读取文件
std::expected<std::string, FileError> read_file(const std::string& path) {
    std::ifstream f(path);
    if (!f) return std::unexpected(FileError::not_found);

    std::ostringstream ss;
    ss << f.rdbuf();
    return ss.str();
}

// 步骤 2:解析 JSON 配置(简化示例)
struct AppConfig {
    std::string name;
    int port;
    bool debug;
};

std::expected<AppConfig, FileError> parse_config(const std::string& content) {
    // 实际项目中使用 JSON 库
    if (content.empty())
        return std::unexpected(FileError::invalid_format);

    // 简化: 假设解析成功
    return AppConfig{.name = "MyApp", .port = 8080, .debug = false};
}

// 步骤 3:验证配置
std::expected<AppConfig, FileError> validate_config(AppConfig config) {
    if (config.port < 1 || config.port > 65535)
        return std::unexpected(FileError::invalid_format);
    return config;
}

// 组合管道
std::expected<AppConfig, FileError> load_app_config(const std::string& path) {
    return read_file(path)
        .and_then(parse_config)
        .and_then(validate_config)
        .or_else([](FileError e) -> std::expected<AppConfig, FileError> {
            std::println(stderr, "配置加载失败: {}", to_string(e));
            return std::unexpected(e);  // 记录后继续传播错误
        });
}

// 使用
int main() {
    auto config = load_app_config("config.json");

    if (config) {
        std::println("启动 {} 在端口 {}", config->name, config->port);
    } else {
        std::println("使用默认配置启动");
        start_with_defaults();
    }
}

组合 expected + optional

// optional: "可能没有" — 不需要知道原因
std::optional<std::string> get_env(const std::string& name) {
    if (auto* val = std::getenv(name.c_str()))
        return std::string(val);
    return std::nullopt;
}

// expected: "可能失败" — 需要知道具体原因
std::expected<Config, std::string> load_config() {
    // 先尝试环境变量(optional — 没有也没关系)
    auto config_path = get_env("APP_CONFIG");

    // 如果环境变量没设,用默认路径
    std::string path = config_path.value_or("/etc/myapp/config.toml");

    // 文件读取可能失败——需要知道原因(expected)
    return read_file(path)
        .and_then(parse_toml_config);
}

自定义错误类

// 更复杂的项目可以定义富错误类型
class AppError {
public:
    enum class Code {
        network_timeout,
        auth_failed,
        data_corrupted,
        not_found
    };

    AppError(Code code, std::string message, std::source_location loc = std::source_location::current())
        : code_(code), message_(std::move(message)), location_(loc) {}

    Code code() const { return code_; }
    const std::string& message() const { return message_; }
    std::string context() const {
        return std::format("{}:{} - [{}] {}",
            location_.file_name(), location_.line(),
            code_name(), message_);
    }

private:
    std::string code_name() const {
        switch (code_) {
            case Code::network_timeout: return "TIMEOUT";
            case Code::auth_failed:     return "AUTH";
            case Code::data_corrupted:  return "CORRUPT";
            case Code::not_found:       return "NOT_FOUND";
        }
        return "UNKNOWN";
    }

    Code code_;
    std::string message_;
    std::source_location location_;
};

// 使用自定义错误类型
using Result<T> = std::expected<T, AppError>;

Result<User> fetch_user(int id) {
    auto response = http_get("/api/users/" + std::to_string(id));
    if (!response)
        return std::unexpected(AppError(
            AppError::Code::network_timeout,
            "请求用户 API 超时"
        ));

    if (response->status == 404)
        return std::unexpected(AppError(
            AppError::Code::not_found,
            "用户 " + std::to_string(id) + " 不存在"
        ));

    return parse_user(response->body);
}

本章小结

  • C 风格返回码容易被忽略,异常有隐式控制流和性能开销
  • std::expected<T, E> 是 C++23 的核心错误处理工具——类型安全、显式、可组合
  • Monadic 操作(and_then、transform、or_else)让错误处理管道优雅简洁
  • 异常仍适用于构造函数失败、真正异常情况、跨库边界等场景
  • noexcept 对移动构造/赋值至关重要——影响 std::vector 等容器的性能选择
  • 选择错误策略要考虑:失败频率、是否需要错误详情、性能要求、团队约定