错误处理与异常对比 ​

概述 ​

C++ 中有多种错误处理机制,每种都有不同的适用场景和权衡。C++23 引入的 std::expected 为开发者提供了一种新的选择。本文对比 C++ 中主要的错误处理方式,帮助你在不同场景下做出合理的选择。

五种错误处理方式对比 ​

特性异常错误码std::optionalstd::expectederrno
错误信息丰富(异常对象)整数无(只有"空")自定义错误类型全局整数
性能(正常路径)零开销零开销零开销零开销零开销
性能(错误路径)很慢(栈展开)零开销零开销零开销零开销
强制调用者处理不强制不强制不强制类型系统强制不强制
函数签名可见不可见需约定可见可见不可见
跨越多层调用自动传播需手动传播需手动monadic 管道需手动
构造/析构安全RAII 配合好容易遗漏安全安全容易遗漏
二进制大小影响增大(展开表)无影响微小微小无影响

基本示例 ​

cpp
#include <iostream>
#include <expected>
#include <optional>
#include <string>
#include <stdexcept>
#include <system_error>
#include <fstream>
#include <cerrno>
#include <cstring>

// ============================
// 方式1:异常
// ============================

namespace with_exception {

double divide(double a, double b) {
    if (b == 0.0) {
        throw std::invalid_argument("除数不能为零");
    }
    return a / b;
}

void demo() {
    try {
        double r = divide(10.0, 0.0);
        std::cout << "结果: " << r << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cout << "异常: " << e.what() << std::endl;
    }
}

} // namespace with_exception

// ============================
// 方式2:错误码
// ============================

namespace with_error_code {

enum class DivideError { Success, DivisionByZero };

DivideError divide(double a, double b, double& result) {
    if (b == 0.0) {
        return DivideError::DivisionByZero;
    }
    result = a / b;
    return DivideError::Success;
}

void demo() {
    double result;
    auto err = divide(10.0, 0.0, result);

    if (err == DivideError::Success) {
        std::cout << "结果: " << result << std::endl;
    } else {
        std::cout << "错误码: DivisionByZero" << std::endl;
    }
}

} // namespace with_error_code

// ============================
// 方式3:std::optional
// ============================

namespace with_optional {

std::optional<double> divide(double a, double b) {
    if (b == 0.0) return std::nullopt;
    return a / b;
}

void demo() {
    auto result = divide(10.0, 0.0);

    if (result) {
        std::cout << "结果: " << *result << std::endl;
    } else {
        std::cout << "失败(不知道什么原因)" << std::endl;
    }

    // value_or 提供默认值
    double r = divide(10.0, 3.0).value_or(0.0);
    std::cout << "value_or: " << r << std::endl;
}

} // namespace with_optional

// ============================
// 方式4:std::expected
// ============================

namespace with_expected {

enum class MathError { DivisionByZero, Overflow };

std::expected<double, MathError> divide(double a, double b) {
    if (b == 0.0) return std::unexpected(MathError::DivisionByZero);
    return a / b;
}

void demo() {
    auto result = divide(10.0, 0.0);

    if (result) {
        std::cout << "结果: " << *result << std::endl;
    } else {
        switch (result.error()) {
            case MathError::DivisionByZero:
                std::cout << "错误: 除零" << std::endl;
                break;
            case MathError::Overflow:
                std::cout << "错误: 溢出" << std::endl;
                break;
        }
    }
}

} // namespace with_expected

// ============================
// 方式5:errno(C 风格)
// ============================

namespace with_errno_style {

void demo() {
    FILE* f = fopen("不存在的文件.txt", "r");
    if (!f) {
        std::cout << "errno: " << errno
                  << " (" << std::strerror(errno) << ")" << std::endl;
    }
}

} // namespace with_errno_style

// ============================
// 实际场景对比:文件读取
// ============================

// 异常版本
namespace file_exception {
std::string read_file(const std::string& path) {
    std::ifstream file(path);
    if (!file.is_open()) {
        throw std::runtime_error("无法打开文件: " + path);
    }
    return std::string(
        (std::istreambuf_iterator<char>(file)),
        std::istreambuf_iterator<char>());
}
} // namespace file_exception

// expected 版本
namespace file_expected {
enum class FileError { NotFound, ReadError };

std::expected<std::string, FileError> read_file(const std::string& path) {
    std::ifstream file(path);
    if (!file.is_open()) {
        return std::unexpected(FileError::NotFound);
    }
    std::string content(
        (std::istreambuf_iterator<char>(file)),
        std::istreambuf_iterator<char>());
    if (file.bad()) {
        return std::unexpected(FileError::ReadError);
    }
    return content;
}
} // namespace file_expected

void file_comparison_demo() {
    // 异常版本
    std::cout << "异常版本:" << std::endl;
    try {
        auto content = file_exception::read_file("test.txt");
        std::cout << "  读取成功" << std::endl;
    } catch (const std::exception& e) {
        std::cout << "  " << e.what() << std::endl;
    }

    // expected 版本
    std::cout << "expected 版本:" << std::endl;
    auto result = file_expected::read_file("test.txt");
    if (result) {
        std::cout << "  读取成功" << std::endl;
    } else {
        std::cout << "  文件未找到" << std::endl;
    }
}

// ============================
// 实际场景:多步操作的错误传播
// ============================

namespace pipeline_comparison {

// 异常版本——错误自动传播
namespace exc {
int parse(const std::string& s) {
    try { return std::stoi(s); }
    catch (...) { throw std::runtime_error("解析失败"); }
}
int validate(int v) {
    if (v < 0 || v > 100) throw std::runtime_error("超出范围");
    return v;
}
double process(int v) { return std::sqrt(v); }

void demo() {
    try {
        auto result = process(validate(parse("49")));
        std::cout << "异常链: " << result << std::endl;
    } catch (const std::exception& e) {
        std::cout << "异常: " << e.what() << std::endl;
    }
}
} // namespace exc

// expected + monadic 版本——错误通过管道传播
namespace exp {
enum class Err { Parse, Range, Compute };

std::expected<int, Err> parse(const std::string& s) {
    try { return std::stoi(s); }
    catch (...) { return std::unexpected(Err::Parse); }
}
std::expected<int, Err> validate(int v) {
    if (v < 0 || v > 100) return std::unexpected(Err::Range);
    return v;
}
std::expected<double, Err> process(int v) {
    return std::sqrt(static_cast<double>(v));
}

void demo() {
    auto result = parse("49")
        .and_then(validate)
        .and_then(process);

    if (result) {
        std::cout << "monadic 链: " << *result << std::endl;
    }
}
} // namespace exp

} // namespace pipeline_comparison

int main() {
    std::cout << "=== 异常 ===" << std::endl;
    with_exception::demo();

    std::cout << "\n=== 错误码 ===" << std::endl;
    with_error_code::demo();

    std::cout << "\n=== optional ===" << std::endl;
    with_optional::demo();

    std::cout << "\n=== expected ===" << std::endl;
    with_expected::demo();

    std::cout << "\n=== errno ===" << std::endl;
    with_errno_style::demo();

    std::cout << "\n=== 文件读取对比 ===" << std::endl;
    file_comparison_demo();

    std::cout << "\n=== 多步操作对比 ===" << std::endl;
    pipeline_comparison::exc::demo();
    pipeline_comparison::exp::demo();

    return 0;
}

选择指南 ​

场景推荐方式原因
构造函数/运算符重载失败异常没有返回值可以用
真正异常的情况(内存耗尽)异常极少发生,不值得每次检查
预期中可能失败的操作(文件/网络)expected调用者必须处理
可能没有值但不算错误optional语义更准确
性能极端敏感(嵌入式/游戏)expected 或错误码避免异常的栈展开开销
与 C API 交互errno + 包装为 expected兼容 C 接口
禁用异常的项目(-fno-exceptions)expected唯一的类型安全选择
多步管道处理expected + monadic链式传播最优雅

异常的优缺点 ​

优点:

  • 正常路径零开销——只有抛出异常时才有成本
  • 自动沿调用栈传播——不需要在每一层手动检查
  • 构造函数/运算符等没有返回值的地方可以用
  • 标准库广泛使用异常

缺点:

  • 错误路径非常慢(栈展开可能耗时数微秒)
  • 增加二进制大小(异常展开表)
  • 函数签名不体现可能的错误
  • 某些环境禁用异常(嵌入式、游戏引擎)
  • 容易被忽略(不 catch 就崩溃)

expected 的优缺点 ​

优点:

  • 类型安全,错误信息丰富
  • 函数签名明确表达可能的失败
  • 正常和错误路径都是零开销
  • monadic 操作支持优雅的链式处理
  • 可以在禁用异常的环境中使用

缺点:

  • 每一层都需要处理或传播错误(monadic 缓解了这个问题)
  • 构造函数中不能使用(没有返回值)
  • C++23 才引入,老项目可能用不了
  • 嵌套层数多时代码可能变复杂

常见问题 ​

在同一个项目中可以混用异常和 expected 吗?

可以。典型做法是在底层库使用 expected 返回错误,在应用层根据需要将 expected 的错误转为异常抛出。两者不冲突。

expected 能完全替代异常吗?

不能。构造函数和运算符重载没有返回值,无法使用 expected。另外,内存分配失败等系统级错误通常还是用异常更合适。

性能差异有多大?

正常路径上几乎没有差异。但在错误路径上,异常的栈展开可能比 expected 的错误传播慢 100-1000 倍(取决于调用深度)。如果错误是预期中经常发生的情况,expected 的性能优势非常明显。

适用场景 ​

  • 需要在多种错误处理机制之间做选择
  • 重构老代码的错误处理方式
  • 设计新项目的错误处理策略
  • 需要理解各种方式的性能特征

注意事项 ​

  • 不要用异常处理预期中的正常情况(如用户输入错误)
  • 不要忽略错误码或 expected 的返回值
  • expected 的 monadic 操作可以大幅减少手动检查的代码
  • 在禁用异常的项目中,expected 是最好的替代品
  • 混用时注意边界——在哪一层从 expected 转为异常

总结 ​

C++ 提供了多种错误处理机制,没有哪一种适合所有场景。异常适合真正异常的、极少发生的错误,正常路径零开销但错误路径很慢。错误码和 errno 简单但容易被忽略,不携带详细信息。std::optional 适合"可能没有值"的语义,但不能表达错误原因。std::expected(C++23)是最新的选择,结合了异常的表达力和错误码的确定性——类型安全、函数签名可见、零运行时开销、支持 monadic 链式处理。实际项目中通常需要混合使用:系统级异常用 try-catch,业务逻辑中预期的失败用 expected,可选值用 optional。