云计算百科
云计算领域专业知识百科平台

C++异常处理全攻略:捕获、自定义与实战

C++异常处理机制:异常捕获、自定义异常与实战应用

一、异常捕获机制

C++通过try-catch块实现异常捕获:

try {
// 可能抛出异常的代码
throw std::runtime_error("示例异常");
}
catch (const std::exception& e) {
std::cerr << "捕获异常: " << e.what() << std::endl;
}
catch (…) { // 捕获所有未处理的异常
std::cerr << "未知异常" << std::endl;
}

  • try块:包裹可能抛出异常的代码
  • catch块:按类型匹配异常,支持多级捕获
  • throw:显式抛出异常对象(如内置类型或自定义类)
二、自定义异常

通过继承标准异常类实现:

class CustomException : public std::exception {
public:
explicit CustomException(const char* msg) : msg_(msg) {}
const char* what() const noexcept override {
return msg_;
}
private:
const char* msg_;
};

// 使用示例
throw CustomException("自定义异常信息");

  • 必须重写what()方法返回异常描述
  • 建议继承std::runtime_error或std::logic_error
三、实战应用场景
  • 资源管理异常
  • void readFile(const std::string& path) {
    std::ifstream file(path);
    if (!file.is_open())
    throw std::ios_base::failure("文件打开失败");

    // RAII机制确保资源释放
    // …
    }

  • 参数校验异常
  • double divide(int a, int b) {
    if (b == 0)
    throw std::invalid_argument("除数不能为零");
    return static_cast<double>(a) / b;
    }

  • 系统调用异常
  • void connectDatabase() {
    if (!db_connection.establish())
    throw DatabaseException("数据库连接失败", error_code);
    }

    四、异常安全等级
  • 基本保证:异常发生后对象仍处于有效状态
  • 强保证:操作要么完全成功,要么状态回滚
  • 不抛保证:使用noexcept声明不抛出异常
  • void criticalOperation() noexcept; // C++11起支持

    五、最佳实践
  • 避免在析构函数中抛出异常
  • 使用智能指针管理资源(如std::unique_ptr)
  • 优先选择标准异常类型:
    • std::runtime_error:运行时错误
    • std::logic_error:逻辑错误
    • std::out_of_range:越界访问
  • 异常类型层级: $$ \\begin{array}{c} \\text{std::exception} \\ \\downarrow \\ \\text{std::runtime_error} \\ \\downarrow \\ \\text{CustomException} \\end{array} $$
  • 注:异常处理会增加约5-10%的性能开销,关键性能模块可使用错误码替代。

    赞(0)
    未经允许不得转载:网硕互联帮助中心 » C++异常处理全攻略:捕获、自定义与实战
    分享到: 更多 (0)

    评论 抢沙发

    评论前必须登录!