C++程序设计语言笔记——基本功能:非常处置处罚

打印 上一主题 下一主题

主题 977|帖子 977|积分 2933

0 在设计初期尽早确定非常处置处罚战略。

在C++中,设计初期的非常处置处罚战略必要细密结合语言特性(如RAII、非常安全品级、智能指针)和性能要求。以下是一套针对C++的非常处置处罚设计框架,包罗代码示例和最佳实践:

1. 非常分类与标准化设计

1.1 非常类型层级

  1. #include <stdexcept>
  2. #include <string>
  3. // 自定义业务异常基类(继承标准异常)
  4. class BusinessException : public std::runtime_error {
  5. public:
  6.     explicit BusinessException(const std::string& msg, int code = 0)
  7.         : std::runtime_error(msg), error_code(code) {}
  8.    
  9.     int get_code() const noexcept { return error_code; }
  10. private:
  11.     int error_code;
  12. };
  13. // 具体业务异常(示例:订单异常)
  14. class OrderException : public BusinessException {
  15. public:
  16.     enum ErrorCode { NOT_FOUND = 1001, INVALID_STATE = 1002 };
  17.     explicit OrderException(ErrorCode code, const std::string& details = "")
  18.         : BusinessException("OrderError: " + details, code) {}
  19. };
复制代码
1.2 错误码规范

  1. // 使用强类型enum定义错误域
  2. namespace ErrorDomain {
  3.     enum class Database { CONNECTION_FAILED = 2001, TIMEOUT = 2002 };
  4.     enum class Network { API_FAILURE = 3001, RATE_LIMITED = 3002 };
  5. }
  6. // 异常中携带错误域信息
  7. class TechnicalException : public std::runtime_error {
  8. public:
  9.     template <typename T>
  10.     TechnicalException(T code, const std::string& msg)
  11.         : std::runtime_error(msg), error_code(static_cast<int>(code)) {}
  12.    
  13.     int get_code() const noexcept { return error_code; }
  14. private:
  15.     int error_code;
  16. };
复制代码

2. 非常处置处罚机制

2.1 全局非常处置处罚

  1. #include <iostream>
  2. #include <cstdlib>
  3. // 设置全局异常处理器(适用于未被捕获的异常)
  4. void global_handler() {
  5.     try {
  6.         if (auto ex = std::current_exception()) {
  7.             std::rethrow_exception(ex);
  8.         }
  9.     } catch (const BusinessException& e) {
  10.         std::cerr << "[Business Error] Code: " << e.get_code()
  11.                   << ", Msg: " << e.what() << "\n";
  12.     } catch (const std::exception& e) {
  13.         std::cerr << "[Fatal] " << e.what() << "\n";
  14.     }
  15.     // 安全终止或重启逻辑
  16.     std::abort();
  17. }
  18. int main() {
  19.     std::set_terminate(global_handler);
  20.     // 主逻辑...
  21. }
复制代码
2.2 防御性编程与左券

  1. // 使用GSL(Guidelines Support Library)进行契约检查
  2. #include <gsl/gsl_assert>
  3. void process_order(Order& order) {
  4.     Expects(order.is_valid()); // 前置条件检查,失败则终止
  5.     // ...
  6. }
  7. // 参数校验(抛出受检异常)
  8. void validate_input(const std::string& input) {
  9.     if (input.empty()) {
  10.         throw BusinessException("Input cannot be empty", 400);
  11.     }
  12. }
复制代码

3. 资源管理与非常安全

3.1 RAII模式保障资源开释

  1. class DatabaseConnection {
  2. public:
  3.     DatabaseConnection() {
  4.         if (!connect()) throw TechnicalException(ErrorDomain::Database::CONNECTION_FAILED, "DB unreachable");
  5.     }
  6.     ~DatabaseConnection() noexcept { disconnect(); }
  7.     // 禁用拷贝,允许移动
  8.     DatabaseConnection(const DatabaseConnection&) = delete;
  9.     DatabaseConnection& operator=(const DatabaseConnection&) = delete;
  10.     DatabaseConnection(DatabaseConnection&&) = default;
  11.     DatabaseConnection& operator=(DatabaseConnection&&) = default;
  12. private:
  13.     bool connect() { /* ... */ }
  14.     void disconnect() noexcept { /* ... */ }
  15. };
  16. // 使用示例
  17. void query_data() {
  18.     DatabaseConnection conn; // 资源获取即初始化
  19.     // 若此处抛出异常,conn析构会自动调用disconnect()
  20.     // ...
  21. }
复制代码
3.2 智能指针管理动态资源

  1. void process_file(const std::string& path) {
  2.     auto file = std::make_unique<std::ifstream>(path);
  3.     if (!file->is_open()) {
  4.         throw TechnicalException(ErrorDomain::IO::FILE_OPEN_FAILED, path);
  5.     }
  6.     // 即使后续操作抛出异常,unique_ptr会确保文件关闭
  7.     // ...
  8. }
复制代码

4. 性能优化与高级本领

4.1 noexcept与移动语义

  1. class Buffer {
  2. public:
  3.     Buffer(size_t size) : data_(new char[size]) {}
  4.    
  5.     // 移动构造函数标记为noexcept,确保容器操作安全
  6.     Buffer(Buffer&& other) noexcept : data_(std::exchange(other.data_, nullptr)) {}
  7.    
  8.     ~Buffer() noexcept { delete[] data_; }
  9. private:
  10.     char* data_;
  11. };
  12. // 标记不会失败的函数
  13. void log_message(const std::string& msg) noexcept {
  14.     // 即使此处抛出异常,程序会终止(符合noexcept约定)
  15.     std::cout << msg << "\n";
  16. }
复制代码
4.2 非常替代方案(可选)

  1. // 使用std::optional返回可能失败的操作
  2. std::optional<int> safe_divide(int a, int b) {
  3.     if (b == 0) return std::nullopt;
  4.     return a / b;
  5. }
  6. // 使用std::expected(C++23或第三方库)
  7. template <typename T, typename E>
  8. using expected = /* 类似Rust Result类型的实现 */;
  9. expected<Data, Error> fetch_data() {
  10.     if (/* 失败条件 */) return unexpected(Error::NETWORK_FAILURE);
  11.     return Data{/* ... */};
  12. }
复制代码

5. 测试与调试战略

5.1 单元测试非常路径

  1. #define CATCH_CONFIG_MAIN
  2. #include <catch2/catch.hpp>
  3. TEST_CASE("Order validation throws on invalid state") {
  4.     Order order(/* 无效状态 */);
  5.     REQUIRE_THROWS_AS(order.confirm(), OrderException);
  6.     REQUIRE_THROWS_WITH(order.cancel(), "Order is already completed");
  7. }
复制代码
5.2 静态分析工具

  1. # 使用Clang-Tidy检查异常安全
  2. clang-tidy -checks='modernize-use-noexcept, bugprone-exception-escape' src/*.cpp
复制代码

6. 设计原则总结

原则C++实现方法示例工具/语法资源安全RAII + 智能指针unique_ptr, 自定义RAII类非常中立确保析构函数不抛非常~MyClass() noexcept {…}强非常包管先修改副本,再swapstd::swap, copy-and-swap性能敏感区禁用非常,改用错误码(-fno-exceptions)Google的禁用非常规范跨模块边界C接口封装非常为错误码extern “C” + try-catch块
完整示例:非常安全的事务操纵

  1. class Transaction {
  2. public:
  3.     void execute() {
  4.         auto backup = current_state_; // 强异常保证:先准备副本
  5.         modify_state();               // 可能抛出异常的操作
  6.         current_state_.swap(backup);  // 无异常则提交更改
  7.     }
  8. private:
  9.     State current_state_;
  10.     void modify_state() { /* ...可能抛出... */ }
  11. };
  12. void business_operation() {
  13.     try {
  14.         Transaction tx;
  15.         tx.execute();
  16.     } catch (const BusinessException& e) {
  17.         // 业务级恢复逻辑
  18.         logger.log_rollback(e);
  19.         throw; // 重新抛出给上层
  20.     }
  21. }
复制代码

决议树:何时利用非常?

  1. 是否违反函数的前置条件? ——是——> 使用断言(Expects/Ensures)
  2.                               |
  3.                              否
  4.                               |
  5. 是否可恢复的预期错误? ————是——> 抛出业务异常
  6.                               |
  7.                              否
  8.                               |
  9. 是否程序无法继续执行? ————是——> 抛技术异常/终止
  10.                               |
  11.                              否
  12.                               |
  13.                         使用错误码或optional
复制代码
通过早期建立这些战略,可使C++项目在维护性、性能和安全之间取得平衡。发起将核心规则写入团队的《C++非常处置处罚指南》,并通过代码审查确保一致性。
1 当无法完成既定使命时抛出非常。

在C++中,当函数无法完成其承诺的使命时,抛出非常是一种清晰的错误流传方式。以下是针对这一场景的详细设计战略和代码实现指南:

1. 非常抛出原则

1.1 明确抛出条件

  1. // 示例:文件加载失败时抛出异常
  2. class FileLoader {
  3. public:
  4.     std::string load(const std::string& path) {
  5.         std::ifstream file(path);
  6.         if (!file.is_open()) {
  7.             throw FileIOException("Cannot open file: " + path, ErrorCode::FILE_NOT_FOUND);
  8.         }
  9.         // 读取文件内容...
  10.         if (file.bad()) {
  11.             throw FileIOException("Read error", ErrorCode::IO_ERROR);
  12.         }
  13.         return content;
  14.     }
  15. };
复制代码
1.2 利用标准非常类型或继承体系

  1. #include <stdexcept>
  2. #include <string>
  3. // 自定义异常类型(继承自std::runtime_error)
  4. class NetworkException : public std::runtime_error {
  5. public:
  6.     enum class ErrorCode { TIMEOUT, CONNECTION_REFUSED };
  7.     NetworkException(ErrorCode code, const std::string& details)
  8.         : std::runtime_error(details), code_(code) {}
  9.     ErrorCode code() const noexcept { return code_; }
  10. private:
  11.     ErrorCode code_;
  12. };
  13. // 使用示例
  14. void connect_to_server() {
  15.     if (/* 连接超时 */) {
  16.         throw NetworkException(NetworkException::ErrorCode::TIMEOUT, "Timeout after 30s");
  17.     }
  18. }
复制代码

2. 非常安全品级设计

2.1 基本非常安全(Basic Guarantee)

  1. class DatabaseTransaction {
  2. public:
  3.     void execute() {
  4.         auto old_state = current_state_; // 备份状态
  5.         try {
  6.             modify_database(); // 可能抛出异常的操作
  7.             current_state_ = new_state_;
  8.         } catch (...) {
  9.             current_state_ = old_state; // 回滚到之前状态
  10.             throw;
  11.         }
  12.     }
  13. };
复制代码
2.2 强非常安全(Strong Guarantee)

  1. class ConfigManager {
  2. public:
  3.     void update_config(const Config& new_config) {
  4.         auto temp = std::make_unique<Config>(new_config); // 先在临时对象操作
  5.         validate_config(*temp);  // 可能抛出
  6.         config_.swap(temp);      // 无异常则提交(原子操作)
  7.     }
  8. };
复制代码

3. 资源管理战略

3.1 RAII主动开释资源

  1. class SafeFileHandle {
  2. public:
  3.     explicit SafeFileHandle(const std::string& path)
  4.         : handle_(fopen(path.c_str(), "r")) {
  5.         if (!handle_) {
  6.             throw FileIOException("Open failed: " + path);
  7.         }
  8.     }
  9.     ~SafeFileHandle() noexcept {
  10.         if (handle_) fclose(handle_);
  11.     }
  12.     // 禁用拷贝,允许移动
  13.     SafeFileHandle(const SafeFileHandle&) = delete;
  14.     SafeFileHandle& operator=(const SafeFileHandle&) = delete;
  15.     SafeFileHandle(SafeFileHandle&&) = default;
  16.     SafeFileHandle& operator=(SafeFileHandle&&) = default;
  17. private:
  18.     FILE* handle_;
  19. };
  20. // 使用示例
  21. void process_file() {
  22.     SafeFileHandle file("data.bin"); // 异常安全
  23.     // 使用文件句柄...
  24. }
复制代码

4. 错误类型与上下文传递

4.1 携带详细错误信息

  1. class PaymentException : public std::runtime_error {
  2. public:
  3.     PaymentException(const std::string& msg,
  4.                     int user_id,
  5.                     const std::string& order_no)
  6.         : std::runtime_error(msg),
  7.           user_id_(user_id),
  8.           order_no_(order_no) {}
  9.     int user_id() const noexcept { return user_id_; }
  10.     const std::string& order_no() const noexcept { return order_no_; }
  11. private:
  12.     int user_id_;
  13.     std::string order_no_;
  14. };
  15. // 抛出示例
  16. void process_payment(int user_id, const Order& order) {
  17.     if (order.amount <= 0) {
  18.         throw PaymentException("Invalid amount", user_id, order.id);
  19.     }
  20. }
复制代码

5. 非常处置处罚最佳实践

5.1 顶层非常捕获

  1. int main() {
  2.     try {
  3.         run_application(); // 主业务逻辑
  4.     } catch (const NetworkException& ex) {
  5.         std::cerr << "Network Error: " << ex.what()
  6.                   << " Code: " << static_cast<int>(ex.code()) << "\n";
  7.         return 1;
  8.     } catch (const std::exception& ex) {
  9.         std::cerr << "Fatal Error: " << ex.what() << "\n";
  10.         return 2;
  11.     } catch (...) {
  12.         std::cerr << "Unknown exception occurred\n";
  13.         return 3;
  14.     }
  15.     return 0;
  16. }
复制代码
5.2 非常与日记集成

  1. void handle_request() {
  2.     try {
  3.         // 业务逻辑...
  4.     } catch (const BusinessException& ex) {
  5.         logger.error("Business failure: {}", ex.what());
  6.         throw;
  7.     } catch (const std::exception& ex) {
  8.         logger.error("Technical failure: {}", ex.what());
  9.         throw AppException("Internal error"); // 包装为通用异常
  10.     }
  11. }
复制代码

6. 性能敏感场景替代方案

6.1 禁用非常(-fno-exceptions)

  1. // 使用错误码返回结果
  2. enum class ErrorCode { OK, FILE_NOT_FOUND, INVALID_DATA };
  3. ErrorCode parse_data(const std::string& input, Data& output) {
  4.     if (input.empty()) return ErrorCode::INVALID_DATA;
  5.     // 解析逻辑...
  6.     return ErrorCode::OK;
  7. }
  8. // 调用方处理
  9. ErrorCode err = parse_data(raw_input, data);
  10. if (err != ErrorCode::OK) {
  11.     handle_error(err);
  12. }
复制代码
6.2 利用std:ptional(C++17)

  1. std::optional<Image> load_image(const std::string& path) {
  2.     if (!file_exists(path)) return std::nullopt;
  3.     // 加载图像...
  4.     return Image(pixels);
  5. }
  6. // 调用方
  7. auto img = load_image("photo.jpg");
  8. if (!img) {
  9.     show_error("Image not loaded");
  10. }
复制代码

7. 非常测试战略

7.1 单元测试非常路径

  1. #include <catch2/catch.hpp>
  2. TEST_CASE("Invalid payment amount throws") {
  3.     Order test_order{ .id = "A1001", .amount = -50 };
  4.     REQUIRE_THROWS_AS(process_payment(101, test_order), PaymentException);
  5. }
  6. TEST_CASE("Network timeout handled") {
  7.     mock_server.set_response_delay(60s); // 模拟超时
  8.     REQUIRE_THROWS_MATCHES(
  9.         connect_to_server(),
  10.         NetworkException,
  11.         Catch::Matchers::Message("Timeout after 30s")
  12.     );
  13. }
复制代码

决议表:何时抛出非常?

场景处置处罚方式示例违反函数前置条件抛出非常或终止程序if (ptr == nullptr) throw ...关键资源获取失败(文件、网络)立即抛出非常文件打开失败、数据库毗连断开外部服务返回不可规复错误抛出携带上下文的业务非常付出网关返回余额不敷数据校验失败且无法继承流程抛出带错误码的验证非常用户提交的表单数据非法必要跨多层调用处置处罚错误抛出非常而非逐层返回错误码深层嵌套的业务逻辑错误
关键设计总结


  • 明确语义:每个非常类型对应详细的错误场景,避免通用std::exception直接抛出
  • 资源安全:结合RAII和智能指针确保非常发生时资源主动开释
  • 性能衡量:在及时体系中评估非常开销,须要时利用错误码
  • 文档左券:在函数注释中明确说明可能抛出的非常类型
  • 统一处置处罚:在应用入口集中捕获未处置处罚非常,记录日记后安全退出
通过遵循这些准则,可在C++项目中构建清晰、健壮的非常处置处罚体系,使错误处置处罚逻辑成为代码质量的上风而非负担。
2 用非常机制处置处罚错误。

在C++中,利用非常机制处置处罚错误是一种有效的方法,能够在错误发生时将控制流转移到合适的处置处罚代码,保持程序结构的清晰和健壮性。以下是分步说明和示例:

1. 定义非常类

继承自标准非常类(如std::runtime_error),以携带特定错误信息。
  1. #include <stdexcept>
  2. #include <string>
  3. // 自定义异常类示例
  4. class FileIOException : public std::runtime_error {
  5. public:
  6.     enum class ErrorCode { FileNotFound, PermissionDenied, ReadError };
  7.     FileIOException(const std::string& message, ErrorCode code)
  8.         : std::runtime_error(message), error_code(code) {}
  9.     ErrorCode getCode() const noexcept { return error_code; }
  10. private:
  11.     ErrorCode error_code;
  12. };
复制代码

2. 抛出非常

在检测到错误时,利用throw关键字抛出非常对象。
  1. #include <fstream>
  2. void loadFile(const std::string& filename) {
  3.     std::ifstream file(filename);
  4.     if (!file.is_open()) {
  5.         throw FileIOException("无法打开文件: " + filename,
  6.                              FileIOException::ErrorCode::FileNotFound);
  7.     }
  8.     // 读取文件内容...
  9.     if (file.fail()) {
  10.         throw FileIOException("读取文件失败",
  11.                              FileIOException::ErrorCode::ReadError);
  12.     }
  13. }
复制代码

3. 捕获并处置处罚非常

利用try-catch块捕获非常,并根据类型处置处罚。
  1. int main() {
  2.     try {
  3.         loadFile("data.txt");
  4.     } catch (const FileIOException& e) {
  5.         std::cerr << "文件错误: " << e.what()
  6.                   << ",错误码: " << static_cast<int>(e.getCode()) << std::endl;
  7.         // 处理文件错误,如重试或退出
  8.         return 1;
  9.     } catch (const std::exception& e) {
  10.         std::cerr << "标准异常: " << e.what() << std::endl;
  11.         return 2;
  12.     } catch (...) {
  13.         std::cerr << "未知异常发生!" << std::endl;
  14.         return 3;
  15.     }
  16.     return 0;
  17. }
复制代码

4. 资源管理(RAII)

利用对象的析构函数主动开释资源,避免资源走漏。
  1. class SafeFileHandler {
  2. public:
  3.     explicit SafeFileHandler(const std::string& filename)
  4.         : file_(filename) {
  5.         if (!file_.is_open()) {
  6.             throw FileIOException("文件打开失败",
  7.                                  FileIOException::ErrorCode::FileNotFound);
  8.         }
  9.     }
  10.     ~SafeFileHandler() {
  11.         if (file_.is_open()) {
  12.             file_.close(); // 确保文件关闭
  13.         }
  14.     }
  15.     // 禁用拷贝,允许移动
  16.     SafeFileHandler(const SafeFileHandler&) = delete;
  17.     SafeFileHandler& operator=(const SafeFileHandler&) = delete;
  18.     SafeFileHandler(SafeFileHandler&&) = default;
  19.     SafeFileHandler& operator=(SafeFileHandler&&) = default;
  20.     void readData() {
  21.         // 读取操作,可能抛出异常
  22.     }
  23. private:
  24.     std::ifstream file_;
  25. };
  26. void processFile() {
  27.     SafeFileHandler file("data.txt"); // RAII管理资源
  28.     file.readData(); // 即使此处抛出异常,file的析构函数仍会关闭文件
  29. }
复制代码

5. 非常安全包管

确保操纵在非常发生后仍保持数据一致性。
强非常安全示例(Copy-and-Swap)

  1. class DatabaseTransaction {
  2. public:
  3.     void updateRecord(int id, const std::string& newData) {
  4.         auto oldData = data_; // 备份当前数据
  5.         data_ = newData;      // 修改数据(可能失败的操作)
  6.         if (!commitToDatabase()) {
  7.             data_ = oldData; // 失败则恢复
  8.             throw std::runtime_error("提交数据库失败");
  9.         }
  10.     }
  11. private:
  12.     std::string data_;
  13.     bool commitToDatabase() { /* 模拟数据库提交 */ return false; }
  14. };
复制代码

6. 性能优化

在性能敏感代码中,避免频仍抛出非常,改用错误码。
  1. // 返回错误码而非抛出异常
  2. enum class ErrorCode { Success, InvalidInput, NetworkError };
  3. ErrorCode processRequest(Request& req) {
  4.     if (!req.isValid()) {
  5.         return ErrorCode::InvalidInput;
  6.     }
  7.     // 处理请求...
  8.     return ErrorCode::Success;
  9. }
  10. // 调用方处理
  11. ErrorCode result = processRequest(request);
  12. if (result != ErrorCode::Success) {
  13.     handleError(result);
  14. }
复制代码

7. 测试非常路径

利用测试框架验证非常是否正确抛出。
  1. #define CATCH_CONFIG_MAIN
  2. #include <catch2/catch.hpp>
  3. TEST_CASE("加载不存在的文件应抛出异常") {
  4.     REQUIRE_THROWS_AS(loadFile("nonexistent.txt"), FileIOException);
  5. }
  6. TEST_CASE("无效输入返回错误码") {
  7.     Request invalidReq;
  8.     CHECK(processRequest(invalidReq) == ErrorCode::InvalidInput);
  9. }
复制代码

总结


  • 明确非常用途:仅对不可规复或关键错误利用非常。
  • 资源管理:结合RAII确保资源安全开释。
  • 非常安全:设计操纵包管基本或强非常安全。
  • 分层处置处罚:在得当层级捕获非常(如UI层捕获并显示错误)。
  • 性能考量:避免在频仍实验路径中利用非常。
  • 文档化:在函数注释中注明可能抛出的非常类型。
通过公道利用非常机制,可以明显提升代码的可读性和健壮性,将错误处置处罚逻辑与业务逻辑分离,便于维护和调试。
3 为特定使命设计用户自定义非常类型(而非内置类型)。

在设计用户自定义非常类型时,遵循以下步调可以确保其高效性、安全性和易用性:

1. 定义底子非常类

创建基类 BaseException,包罗核心属性和方法,供所有详细非常继承。
  1. #include <string>
  2. #include <exception> // 可选,若不继承标准异常则无需包含
  3. // 完全独立的自定义异常基类(不继承std::exception)
  4. class BaseException {
  5. public:
  6.     BaseException(const std::string& message, int code = 0)
  7.         : message_(message), error_code_(code) {}
  8.     virtual ~BaseException() = default; // 虚析构函数防止切片
  9.     virtual const char* what() const noexcept {
  10.         return message_.c_str();
  11.     }
  12.     int code() const noexcept {
  13.         return error_code_;
  14.     }
  15. protected:
  16.     std::string message_;
  17.     int error_code_;
  18. };
复制代码

2. 创建特定使命非常类

针对差别错误场景,派生详细的非常类,添加使命相关数据。
示例1:文件操纵非常

  1. class FileIOException : public BaseException {
  2. public:
  3.     enum class Operation { Read, Write, Open };
  4.     FileIOException(Operation op, const std::string& path, int sys_errno = 0)
  5.         : BaseException(formatMessage(op, path, sys_errno), sys_errno),
  6.           operation_(op), file_path_(path) {}
  7.     Operation operation() const { return operation_; }
  8.     const std::string& path() const { return file_path_; }
  9. private:
  10.     static std::string formatMessage(Operation op, const std::string& path, int err) {
  11.         std::string opStr;
  12.         switch (op) {
  13.             case Operation::Read: opStr = "读取"; break;
  14.             case Operation::Write: opStr = "写入"; break;
  15.             case Operation::Open: opStr = "打开"; break;
  16.         }
  17.         return opStr + "文件失败: " + path + " (系统错误码: " + std::to_string(err) + ")";
  18.     }
  19.     Operation operation_;
  20.     std::string file_path_;
  21. };
复制代码
示例2:网络请求非常

  1. #include <chrono>
  2. class NetworkException : public BaseException {
  3. public:
  4.     NetworkException(const std::string& url,
  5.                     const std::string& response,
  6.                     int http_status)
  7.         : BaseException("HTTP请求失败: " + url + " [状态码: " + std::to_string(http_status) + "]", http_status),
  8.           url_(url), response_(response), http_status_(http_status),
  9.           timestamp_(std::chrono::system_clock::now()) {}
  10.     const std::string& url() const { return url_; }
  11.     const std::string& response() const { return response_; }
  12.     std::time_t timestamp() const {
  13.         return std::chrono::system_clock::to_time_t(timestamp_);
  14.     }
  15. private:
  16.     std::string url_;
  17.     std::string response_;
  18.     int http_status_;
  19.     std::chrono::system_clock::time_point timestamp_;
  20. };
复制代码

3. 抛出非常

在检测到错误时,构造并抛出详细非常对象。
  1. #include <fstream>
  2. #include <cstring> // 用于strerror
  3. void readFile(const std::string& path) {
  4.     std::ifstream file(path);
  5.     if (!file) {
  6.         throw FileIOException(FileIOException::Operation::Open, path, errno);
  7.     }
  8.     std::string content;
  9.     if (!std::getline(file, content)) {
  10.         throw FileIOException(FileIOException::Operation::Read, path, errno);
  11.     }
  12. }
复制代码

4. 捕获并处置处罚非常

利用try-catch块按类型处置处罚差别非常,访问其特定属性。
  1. int main() {
  2.     try {
  3.         readFile("data.txt");
  4.         // 假设此处有网络请求...
  5.     } catch (const FileIOException& e) {
  6.         std::cerr << "[文件错误] 操作类型: " << static_cast<int>(e.operation())
  7.                   << "\n路径: " << e.path()
  8.                   << "\n错误信息: " << e.what() << std::endl;
  9.     } catch (const NetworkException& e) {
  10.         std::cerr << "[网络错误] URL: " << e.url()
  11.                   << "\n响应内容: " << e.response()
  12.                   << "\n时间: " << std::ctime(&e.timestamp())
  13.                   << "错误码: " << e.code() << std::endl;
  14.     } catch (const BaseException& e) {
  15.         std::cerr << "[通用错误] " << e.what()
  16.                   << " (代码: " << e.code() << ")" << std::endl;
  17.     } catch (...) {
  18.         std::cerr << "未知异常发生!" << std::endl;
  19.     }
  20.     return 0;
  21. }
复制代码

5. 高级特性增强

5.1 支持链式非常(错误缘故原由追溯)

  1. class BaseException {
  2. public:
  3.     BaseException(const std::string& message, BaseException* cause = nullptr)
  4.         : message_(message), cause_(cause) {}
  5.     const BaseException* cause() const { return cause_.get(); }
  6.     // 递归打印异常链
  7.     void printTrace(std::ostream& os, int level = 0) const {
  8.         os << std::string(level * 2, ' ') << "[" << level << "] " << what() << "\n";
  9.         if (cause_) {
  10.             cause_->printTrace(os, level + 1);
  11.         }
  12.     }
  13. private:
  14.     std::unique_ptr<BaseException> cause_;
  15. };
  16. // 使用示例
  17. try {
  18.     try {
  19.         connectDatabase(); // 可能抛出NetworkException
  20.     } catch (BaseException& e) {
  21.         throw BaseException("数据库连接失败", new NetworkException(e)); // 包装原因
  22.     }
  23. } catch (const BaseException& e) {
  24.     e.printTrace(std::cerr);
  25. }
复制代码
5.2 序列化非常信息(用于日记或网络传输)

  1. #include <nlohmann/json.hpp> // 使用JSON库
  2. class NetworkException : public BaseException {
  3. public:
  4.     nlohmann::json toJson() const {
  5.         return {
  6.             {"type", "NetworkException"},
  7.             {"url", url_},
  8.             {"http_status", http_status_},
  9.             {"timestamp", timestamp_.time_since_epoch().count()},
  10.             {"message", message_},
  11.             {"code", error_code_}
  12.         };
  13.     }
  14. };
  15. // 日志记录示例
  16. catch (const NetworkException& e) {
  17.     logger.error(e.toJson().dump());
  18. }
复制代码

6. 设计原则总结

原则实现方法明确语义每个非常类对应详细错误场景(如FileIOException、NetworkException)丰富上下文在非常类中添加使命相关数据(路径、错误码、时间戳等)类型安全通过继承层次区分错误类型,避免利用通用非常资源安全利用智能指针管理动态分配的缘故原由非常(std::unique_ptr<BaseException>)可扩展性通过基类提供统一接口(what()、code()),派生类扩展数据兼容性可选:若需与标准非常交互,可多重继承std::exception(但根据用户需求省略)
性能优化发起


  • 避免频仍抛出:在性能关键路径(如循环内部)优先利用错误码。
  • 移动语义:确保非常类支持移动构造,减少拷贝开销。
    1. class BaseException {
    2. public:
    3.     BaseException(BaseException&&) = default;
    4.     BaseException& operator=(BaseException&&) = default;
    5. };
    复制代码
  • 轻量级设计:避免在非常类中存储过大数据(如完整响应内容可存指针)。

单元测试示例

  1. #define CATCH_CONFIG_MAIN
  2. #include <catch2/catch.hpp>
  3. TEST_CASE("读取不存在文件应抛出FileIOException") {
  4.     REQUIRE_THROWS_AS(readFile("nonexistent.txt"), FileIOException);
  5. }
  6. TEST_CASE("NetworkException序列化包含正确URL") {
  7.     NetworkException e("https://api.example.com", "Not Found", 404);
  8.     auto json = e.toJson();
  9.     REQUIRE(json["url"] == "https://api.example.com");
  10.     REQUIRE(json["http_status"] == 404);
  11. }
复制代码

通过以上步调,您可以为特定使命设计出功能强大、信息丰富的自定义非常类型,提升代码的可维护性和错误处置处罚能力。
4 假如由于某种缘故原由你无法利用非常,尽量模仿其机制。

在无法利用C++非常机制的情况下(如嵌入式环境、禁用非常的代码规范或性能敏感场景),可以通过以下方法模仿类似非常的错误处置处罚流程,同时保持代码的结构化和安全性:

1. 定义错误类型与返回码

1.1 通用错误码罗列

  1. enum class ErrorCode {
  2.     Success = 0,
  3.     FileNotFound,
  4.     NetworkTimeout,
  5.     InvalidArgument,
  6.     OutOfMemory
  7. };
复制代码
1.2 携带上下文信息的错误对象

  1. struct Error {
  2.     ErrorCode code;
  3.     std::string message;  // 错误描述
  4.     std::string detail;   // 调试信息(如文件路径)
  5.     int sys_errno = 0;    // 系统错误码(如errno)
  6.     // 快速创建错误的辅助方法
  7.     static Error fromFileError(ErrorCode code, const std::string& path, int err) {
  8.         return Error{code, "文件操作失败", "路径: " + path, err};
  9.     }
  10. };
复制代码

2. 错误传递机制

2.1 函数返回错误码

  1. // 返回值 + 错误码输出参数
  2. bool readFile(std::string& content, const std::string& path, Error& err) {
  3.     if (path.empty()) {
  4.         err = Error{ErrorCode::InvalidArgument, "路径为空"};
  5.         return false;
  6.     }
  7.     // 文件操作...
  8.     return true;
  9. }
复制代码
2.2 利用结构体包装结果

  1. template <typename T>
  2. struct Result {
  3.     T value;
  4.     Error error;
  5.     bool ok() const { return error.code == ErrorCode::Success; }
  6. };
  7. Result<std::string> loadConfig(const std::string& path) {
  8.     if (!fileExists(path)) {
  9.         return { {}, Error::fromFileError(ErrorCode::FileNotFound, path, errno) };
  10.     }
  11.     return { readFileContent(path), Error{ErrorCode::Success} };
  12. }
复制代码

3. 错误处置处罚流程模仿

3.1 手动实现"try-catch"逻辑

  1. // 通过宏简化错误检查
  2. #define TRY(expr) \
  3.     { auto result = expr; if (!result.ok()) return result.error; }
  4. // 函数调用链中的错误冒泡
  5. Error initializeSystem() {
  6.     TRY(loadConfig("config.json"));  // 若失败直接返回错误
  7.     TRY(connectToDatabase());
  8.     return Error{ErrorCode::Success};
  9. }
复制代码
3.2 错误处置处罚中央

  1. void handleError(const Error& err) {
  2.     logError(err);  // 记录日志
  3.     if (err.code == ErrorCode::NetworkTimeout) {
  4.         retryOperation();
  5.     } else {
  6.         shutdownGracefully();
  7.     }
  8. }
  9. int main() {
  10.     Error err = initializeSystem();
  11.     if (!err.ok()) {
  12.         handleError(err);
  13.         return 1;
  14.     }
  15.     return 0;
  16. }
复制代码

4. 资源管理(模仿RAII)

4.1 自定义作用域保卫

  1. template <typename Cleanup>
  2. class ScopeGuard {
  3. public:
  4.     ScopeGuard(Cleanup cleanup) : cleanup_(cleanup), active_(true) {}
  5.     ~ScopeGuard() { if (active_) cleanup_(); }
  6.     void dismiss() { active_ = false; }
  7. private:
  8.     Cleanup cleanup_;
  9.     bool active_;
  10. };
  11. // 使用示例:确保文件句柄关闭
  12. Result<void> processFile(const std::string& path) {
  13.     FILE* file = fopen(path.c_str(), "r");
  14.     if (!file) return makeFileError(path);
  15.    
  16.     auto guard = ScopeGuard([&] { fclose(file); });
  17.     // 文件操作...
  18.     guard.dismiss();  // 操作成功时取消关闭
  19.     return success();
  20. }
复制代码

5. 错误流传优化

5.1 错误链追踪

  1. struct Error {
  2.     // ... 其他字段
  3.     std::shared_ptr<Error> cause;  // 错误原因链
  4.     static Error wrap(Error&& current, Error&& cause) {
  5.         current.cause = std::make_shared<Error>(std::move(cause));
  6.         return current;
  7.     }
  8. };
  9. Error fetchData() {
  10.     Error err = downloadFromNetwork();
  11.     if (!err.ok()) {
  12.         return Error::wrap(
  13.             Error{ErrorCode::DataUnavailable, "数据获取失败"},
  14.             std::move(err)
  15.         );
  16.     }
  17.     return success();
  18. }
复制代码

6. 替代方案对比

方法优点缺点返回错误码简朴直观,零开销需手动查抄每个返回值Result结构体类型安全,可携带附加数据代码冗余,需频仍解包setjmp/longjmp真正的非本地跳转不安全(可能跳过析构函数)错误回调函数异步友好粉碎控制流可读性
完整示例:错误处置处罚工作流

  1. Result<int> parseNumber(const std::string& input) {
  2.     if (input.empty()) {
  3.         return {0, Error{ErrorCode::InvalidArgument, "输入为空"}};
  4.     }
  5.     try {
  6.         return {std::stoi(input), {}};
  7.     } catch (const std::exception& e) {
  8.         return {0, Error{ErrorCode::InvalidArgument, e.what()}};
  9.     }
  10. }
  11. Error calculateSum() {
  12.     Result<int> a = parseNumber("42");
  13.     if (!a.ok()) return a.error;
  14.     Result<int> b = parseNumber("abc");
  15.     if (!b.ok()) return b.error;  // 此处会返回解析错误
  16.     std::cout << "Sum: " << (a.value + b.value) << std::endl;
  17.     return {};
  18. }
  19. int main() {
  20.     if (Error err = calculateSum(); !err.ok()) {
  21.         std::cerr << "错误: " << err.message
  22.                   << "\n详情: " << err.detail << std::endl;
  23.         return 1;
  24.     }
  25.     return 0;
  26. }
复制代码

关键设计原则


  • 统一错误接口:所有函数利用类似的错误返回方式(如Result<T>)
  • 错误信息丰富化:携带足够上下文用于调试
  • 资源安全:通过保卫对象模仿RAII
  • 错误处置处罚集中化:在高层级统一处置处罚错误,避免分散的错误查抄
  • 错误链支持:追踪错误根源,类似非常的堆栈回溯
通过这种方式,可以在禁用非常的环境中构建可维护的错误处置处罚体系,同时保持代码的结构化。对于性能关键代码,可进一步优化错误对象的内存分配(如利用预分配错误池)。
5 利用层次化非常处置处罚。

在C++中实现层次化非常处置处罚,需结合体系架构分层设计非常类型和处置处罚逻辑。以下为分层处置处罚战略、代码示例及最佳实践:

1. 分层非常类型设计

1.1 底子非常类(所有非常基类)

  1. #include <string>
  2. #include <exception>
  3. class BaseException : public std::exception {
  4. public:
  5.     BaseException(const std::string& message, int code = 0, const BaseException* cause = nullptr)
  6.         : msg_(message), code_(code), cause_(cause ? cause->clone() : nullptr) {}
  7.     const char* what() const noexcept override { return msg_.c_str(); }
  8.     int code() const noexcept { return code_; }
  9.     const BaseException* cause() const noexcept { return cause_.get(); }
  10.     // 克隆方法用于异常链
  11.     virtual BaseException* clone() const {
  12.         return new BaseException(*this);
  13.     }
  14. protected:
  15.     std::string msg_;
  16.     int code_;
  17.     std::unique_ptr<BaseException> cause_;
  18. };
复制代码
1.2 分层非常派生类

  1. // 数据访问层异常
  2. class DaoException : public BaseException {
  3. public:
  4.     enum ErrorType { CONNECTION_FAILED, QUERY_ERROR };
  5.     DaoException(ErrorType type, const std::string& sql, int db_errno)
  6.         : BaseException(formatMsg(type, sql, db_errno), db_errno),
  7.           sql_(sql), error_type_(type) {}
  8.     ErrorType error_type() const { return error_type_; }
  9.     const std::string& sql() const { return sql_; }
  10.     DaoException* clone() const override {
  11.         return new DaoException(*this);
  12.     }
  13. private:
  14.     static std::string formatMsg(ErrorType type, const std::string& sql, int err) {
  15.         return std::string("DAO Error: ") +
  16.                (type == CONNECTION_FAILED ? "连接失败" : "查询失败") +
  17.                " SQL: " + sql + " Code: " + std::to_string(err);
  18.     }
  19.     std::string sql_;
  20.     ErrorType error_type_;
  21. };
  22. // 业务逻辑层异常
  23. class ServiceException : public BaseException {
  24. public:
  25.     ServiceException(const std::string& bizMsg, int bizCode, const BaseException& cause)
  26.         : BaseException(bizMsg, bizCode, &cause) {}
  27.     ServiceException* clone() const override {
  28.         return new ServiceException(*this);
  29.     }
  30. };
  31. // 用户界面层异常(最终展示给用户)
  32. class UIException : public BaseException {
  33. public:
  34.     UIException(const std::string& userFriendlyMsg)
  35.         : BaseException(userFriendlyMsg) {}
  36. };
复制代码

2. 分层处置处罚战略

2.1 数据访问层(DAO Layer)



  • 职责:捕获数据库原生非常,转换为DaoException
  1. class UserDao {
  2. public:
  3.     User findUser(int id) {
  4.         try {
  5.             executeQuery("SELECT * FROM users WHERE id=" + std::to_string(id));
  6.         } catch (const mysqlpp::Exception& e) { // 假设使用MySQL++
  7.             throw DaoException(DaoException::QUERY_ERROR,
  8.                              e.query(), e.errnum());
  9.         }
  10.         // ...
  11.     }
  12. };
复制代码
2.2 业务逻辑层(Service Layer)



  • 职责:捕获DAO非常,转换为业务语义非常,添加业务上下文
  1. class UserService {
  2. public:
  3.     void transferMoney(int from, int to, double amount) {
  4.         try {
  5.             UserDao dao;
  6.             dao.withdraw(from, amount); // 可能抛出DaoException
  7.             dao.deposit(to, amount);
  8.         } catch (const DaoException& e) {
  9.             throw ServiceException("资金转账失败", 1001, e);
  10.         } catch (const std::invalid_argument& e) {
  11.             // 处理参数错误,不包装直接抛出
  12.             throw;
  13.         }
  14.     }
  15. };
复制代码
2.3 用户界面层(UI Layer)



  • 职责:捕获所有未处置处罚非常,转换为用户友好提示
  1. void onTransferButtonClicked() {
  2.     try {
  3.         UserService service;
  4.         service.transferMoney(getFromId(), getToId(), getAmount());
  5.         showSuccess("转账成功!");
  6.     } catch (const ServiceException& e) {
  7.         // 解析业务错误码
  8.         std::string userMsg = "操作失败: " + std::string(e.what());
  9.         if (e.code() == 1001) userMsg += "(请检查余额)";
  10.         showError(userMsg);
  11.         // 记录详细日志
  12.         logError(e);
  13.     } catch (const std::exception& e) {
  14.         showError("系统错误,请联系管理员");
  15.         logError(e);
  16.     }
  17. }
  18. // 日志记录函数(递归打印异常链)
  19. void logError(const BaseException& e) {
  20.     std::cerr << "ERROR: " << e.what() << " [Code: " << e.code() << "]\n";
  21.     if (auto cause = e.cause()) {
  22.         std::cerr << "Caused by: ";
  23.         logError(*cause);
  24.     }
  25. }
复制代码

3. 关键技术实现

3.1 非常链(Chain of Causality)

  1. // 抛出时包装底层异常
  2. try {
  3.     dao.update(data);
  4. } catch (const DaoException& e) {
  5.     throw ServiceException("更新数据失败", 2001, e);
  6. }
  7. // 日志输出
  8. ERROR: 更新数据失败 [Code: 2001]
  9. Caused by: DAO Error: 查询失败 SQL: UPDATE ... Code: 1062
复制代码
3.2 资源安全(RAII + 非常安全包管)

  1. class Transaction {
  2. public:
  3.     Transaction(Database& db) : db_(db) { db_.begin(); }
  4.     ~Transaction() { if (!committed_) db_.rollback(); }
  5.     void commit() {
  6.         db_.commit();
  7.         committed_ = true;
  8.     }
  9. private:
  10.     Database& db_;
  11.     bool committed_ = false;
  12. };
  13. void businessOperation() {
  14.     Transaction tx(db); // RAII管理事务
  15.     // 多个数据库操作...
  16.     tx.commit(); // 无异常则提交
  17. }
复制代码

4. 分层处置处罚决议树

     
5. 性能优化发起


  • 避免过分包装:仅在跨层边界时包装非常
  • 利用noexcept标记:对不会失败的函数(如简朴getter)利用noexcept
    1. std::string getErrorMessage() const noexcept {
    2.     return msg_;
    3. }
    复制代码
  • 错误码替代:对高频调用的底层函数利用错误码返回
    1. ErrorCode validateInput(const std::string& input) {
    2.     if (input.empty()) return EC_EMPTY_INPUT;
    3.     return EC_SUCCESS;
    4. }
    复制代码

6. 单元测试战略

  1. TEST_CASE("DAO层应正确转换数据库异常") {
  2.     UserDao dao;
  3.     REQUIRE_THROWS_MATCHES(
  4.         dao.findUser(-1),
  5.         DaoException,
  6.         Catch::Predicate<DaoException>([](const DaoException& e) {
  7.             return e.error_type() == DaoException::QUERY_ERROR;
  8.         })
  9.     );
  10. }
  11. TEST_CASE("Service层应包装DAO异常") {
  12.     MockUserDao dao; // 模拟抛出DaoException
  13.     UserService service(dao);
  14.     REQUIRE_THROWS_AS(service.transferMoney(1, 2, 100), ServiceException);
  15. }
复制代码

总结

通过层次化非常处置处罚设计,可实现:

  • 关注点分离:每层专注处置处罚其职责范围内的错误
  • 信息丰富化:非常链携带完整错误上下文
  • 用户友好:UI层隔离技术细节,展示清晰提示
  • 维护性提升:非常类型与业务语义直接关联
关键原则:底层捕获技术非常,高层处置处罚业务语义,顶层包管用户体验。发起结合静态分析工具(如Clang-Tidy)查抄非常安全,确保设计落地。
6 保持非常处置处罚的各个部分尽量简便。

以下是保持C++非常处置处罚简便高效的核心实践和示例:

1. 非常定义简便化

1.1 优先利用标准非常

  1. #include <stdexcept>
  2. void validate_age(int age) {
  3.     if (age < 0) throw std::invalid_argument("年龄不能为负");
  4.     if (age > 150) throw std::out_of_range("年龄超过合理范围");
  5. }
复制代码
1.2 须要时创建最少量的自定义非常

  1. // 仅当需要携带额外数据时创建
  2. class PaymentError : public std::runtime_error {
  3. public:
  4.     int amount;  // 简洁的额外字段
  5.     PaymentError(const std::string& msg, int amt)
  6.         : std::runtime_error(msg), amount(amt) {}
  7. };
复制代码

2. 非常抛出简便化

2.1 快速失败(Fail Fast)

  1. void process_input(const std::string& input) {
  2.     if (input.empty()) throw std::invalid_argument("输入为空"); // 首行校验
  3.     // 后续逻辑...
  4. }
复制代码
2.2 利用noexcept标记不抛非常的函数

  1. // 明确告知编译器此函数不会抛出
  2. std::string format_message(int code) noexcept {
  3.     return "Error-" + std::to_string(code); // 简单操作,确保不抛异常
  4. }
复制代码

3. 非常捕获简便化

3.1 按层处置处罚,避免过分捕获

  1. // 数据访问层
  2. try {
  3.     db.execute(sql);
  4. } catch (const DatabaseTimeout&) {
  5.     throw; // 直接重新抛出给业务层
  6. }
  7. // 业务层
  8. try {
  9.     process_order();
  10. } catch (const DatabaseTimeout& e) {
  11.     retry_operation(); // 业务重试逻辑
  12. } catch (const std::exception& e) {
  13.     log_error(e.what());
  14.     throw ServiceUnavailable(); // 转换为业务异常
  15. }
  16. // UI层
  17. try {
  18.     start_app();
  19. } catch (const ServiceUnavailable&) {
  20.     show_error("服务暂不可用,请稍后重试");
  21. } catch (...) {
  22.     show_error("发生未知错误");
  23. }
复制代码

4. 资源管理简便化

4.1 利用智能指针主动管理

  1. void load_data() {
  2.     auto file = std::make_unique<std::ifstream>("data.bin");
  3.     if (!*file) throw std::runtime_error("无法打开文件");
  4.     // 无需手动关闭,unique_ptr析构自动处理
  5. }
复制代码
4.2 利用标准容器

  1. void process_items() {
  2.     std::vector<Item> items;
  3.     items.reserve(1000); // 预先分配减少异常可能性
  4.     while (auto item = fetch_item()) {
  5.         items.push_back(std::move(item)); // 自动内存管理
  6.     }
  7. }
复制代码

5. 非常安全包管简便化

5.1 基本包管(Basic Guarantee)示例

  1. class Config {
  2.     std::map<std::string, std::string> params;
  3. public:
  4.     void update(const std::string& key, const std::string& value) {
  5.         auto temp = params; // 先复制
  6.         temp[key] = value;   // 修改副本
  7.         params.swap(temp);  // 无异常则提交(强保证)
  8.     }
  9. };
复制代码

6. 全局处置处罚简便化

6.1 设置简便的终止处置处罚器

  1. #include <cstdlib>
  2. #include <iostream>
  3. void terminate_handler() {
  4.     try {
  5.         if (auto ex = std::current_exception()) {
  6.             std::rethrow_exception(ex);
  7.         }
  8.     } catch (const std::exception& e) {
  9.         std::cerr << "未捕获异常: " << e.what() << "\n";
  10.     } catch (...) {
  11.         std::cerr << "未知异常类型\n";
  12.     }
  13.     std::abort();
  14. }
  15. int main() {
  16.     std::set_terminate(terminate_handler);
  17.     // 主逻辑...
  18. }
复制代码

7. 测试简便化

7.1 利用宏简化测试代码

  1. #define REQUIRE_THROWS_MSG(expr, msg) \
  2.     REQUIRE_THROWS_WITH(expr, Catch::Matchers::Contains(msg))
  3. TEST_CASE("支付金额校验") {
  4.     REQUIRE_THROWS_MSG(process_payment(-100), "金额无效");
  5.     REQUIRE_NOTHROW(process_payment(500));
  6. }
复制代码

简便化原则总结

原则实现方式示例避免过分设计优先利用标准非常类型throw std::invalid_argument资源主动管理利用智能指针和容器std::unique_ptr, vector快速失败在函数开始处验证参数if (input.empty()) throw...分层处置处罚每层只处置处罚自己关心的非常DAO层不处置处罚业务非常减少嵌套利用RAII替代try-catch嵌套用unique_ptr而非手动开释明确函数左券用noexcept标记不抛非常的函数void print() noexcept {...}
通过遵循这些简便化原则,可在保持代码健壮性的同时,明显提升可读性和维护性。核心思想:让非常处置处罚逻辑保持简朴、直接和专注,避免不须要的复杂性
7 不要试图捕获每个函数的每个非常。

在C++非常处置处罚中,"不要试图捕获每个函数的每个非常"是保持代码健壮性和可维护性的重要原则。以下为详细实践指南和代码示例:

1. 分层处置处罚原则

1.1 非常捕获的黄金法则

  1. // 错误示例:底层函数过度捕获
  2. void lowLevelFunc() {
  3.     try {
  4.         readFromDevice(); // 物理设备读取
  5.     } catch (...) {      // ❌ 底层捕获所有异常
  6.         log("设备错误");
  7.     }
  8. }
  9. // 正确做法:允许异常向上传播
  10. void businessLogic() {
  11.     try {
  12.         lowLevelFunc();
  13.         processData();
  14.     } catch (const DeviceException& e) { // ✅ 业务层处理
  15.         retryOrAbort(e);
  16.     }
  17. }
复制代码
1.2 各层职责划分

层级处置处罚战略示例操纵底层库函数仅抛出,不处置处罚文件操纵失败抛出io_error业务逻辑层捕获可规复非常,转换业务语义将数据库非常转为业务错误码UI/API层终极捕获,展示友好信息弹窗提示"服务不可用"
2. 资源管理主动化

2.1 利用智能指针避免手动清理

  1. // 无需try-catch的资源管理
  2. void processFile() {
  3.     auto file = std::make_unique<std::ifstream>("data.bin"); // RAII
  4.     if (!*file) throw FileOpenError();
  5.    
  6.     // 即使后续抛出异常,file析构会自动关闭
  7.     parseContent(*file);
  8. }
复制代码
2.2 事务操纵模板

  1. template <typename Func>
  2. void transactionWrapper(Func op) {
  3.     beginTransaction(); // 事务开始
  4.     try {
  5.         op();          // 业务操作
  6.         commit();      // 无异常提交
  7.     } catch (...) {
  8.         rollback();    // 异常回滚
  9.         throw;         // 继续传播
  10.     }
  11. }
  12. // 使用示例
  13. transactionWrapper([] {
  14.     updateAccount(1, -100);  // 扣款
  15.     updateAccount(2, +100);  // 加款
  16. });
复制代码

3. 非常流传战略

3.1 只处置处罚能解决的非常

  1. // 中间件层:仅处理特定异常
  2. void middleware() {
  3.     try {
  4.         callDownstreamService();
  5.     } catch (const TimeoutException&) { // 只处理超时重试
  6.         retry(3);
  7.     } // 其他异常继续传播
  8. }
  9. // 调用方
  10. try {
  11.     middleware();
  12. } catch (const ServiceException& e) {
  13.     showUserError(e); // 最终处理
  14. }
复制代码
3.2 不可规复错误快速失败

  1. void validateConfig(const Config& cfg) {
  2.     if (!cfg.isValid()) {
  3.         logFatal("配置损坏,无法启动");
  4.         std::terminate(); // ❗立即终止
  5.     }
  6. }
复制代码

4. 非常安全包管

4.1 基本非常安全示例

  1. class Document {
  2.     std::vector<Page> pages_;
  3. public:
  4.     void addPage(const Page& p) {
  5.         pages_.push_back(p); // 可能抛出bad_alloc
  6.         // 失败时保持原有pages_不变(基本安全)
  7.     }
  8. };
复制代码
4.2 强非常安全实现

  1. void swapContents(Document& doc, const Page& newPage) {
  2.     auto temp = doc.pages_; // 操作副本
  3.     temp.push_back(newPage);
  4.     doc.pages_.swap(temp);  // 无异常则原子交换(强安全)
  5. }
复制代码

5. 日记与调试辅助

5.1 集中式非常日记

  1. // 全局捕获处理器
  2. void globalHandler() {
  3.     try {
  4.         // ...重新抛出异常
  5.     } catch (const std::exception& e) {
  6.         logException(e);
  7.         if (isCritical(e)) sendAlert();
  8.     }
  9. }
  10. // 结构化日志记录
  11. void logException(const std::exception& e) {
  12.     json log = {
  13.         {"timestamp", getTime()},
  14.         {"type", typeid(e).name()},
  15.         {"message", e.what()},
  16.         {"stack", getStacktrace()}
  17.     };
  18.     logger.write(log);
  19. }
复制代码

关键决议表

场景处置处罚方式代码示例物理资源操纵失败(文件/网络)抛出技术非常,不捕获throw FileIOException(...)业务规则校验失败立即抛出业务非常throw InvalidOrder(...)第三方库错误包装为体系非常向上抛throw DatabaseError(...)内存耗尽等不可规复错误记录后终止程序std::terminate()用户输入校验立即返回错误码,不利用非常return ErrorCode::Invalid
最佳实践总结


  • 抛出清晰:每个非常应携带足够诊断信息(错误码、上下文)
  • 资源无忧:通过RAII和智能指针确保资源主动开释
  • 层级过滤:技术非常在底层抛出,业务层转换语义,UI层友好提示
  • 安全包管:明确函数提供的非常安全品级(基本/强/noexcept)
  • 监控到位:全局处置处罚器记录未捕获非常,结合日记分析
通过遵循这些原则,可在保持代码简便的同时构建健壮的非常处置处罚体系,避免陷入"非常处置处罚反模式"的陷阱。记住:好的非常处置处罚是战略性的,而非事无巨细的战术防御
8 至少提供基本保障。

在C++中,确保代码至少提供 基本非常安全包管(Basic Exception Safety Guarantee)是健壮代码设计的底线。基本包管要求:当非常发生时,程序不泄露资源,所有对象仍处于有效状态(可安全析构),且程序状态保持一致性。以下是详细实现战略和代码示例:

1. RAII(资源获取即初始化)

1.1 利用智能指针管理动态内存

  1. #include <memory>
  2. void process_data(size_t size) {
  3.     auto buffer = std::make_unique<int[]>(size); // 自动管理内存
  4.     // 即使后续操作抛出异常,buffer析构时也会自动释放内存
  5.     fill_buffer(buffer.get(), size);
  6.     save_to_database(buffer.get(), size);
  7. }
复制代码
1.2 自定义RAII类管理文件句柄

  1. #include <fstream>
  2. class SafeFile {
  3. public:
  4.     explicit SafeFile(const std::string& path)
  5.         : file_(path, std::ios::binary) {
  6.         if (!file_) throw std::runtime_error("无法打开文件");
  7.     }
  8.     ~SafeFile() noexcept {
  9.         if (file_.is_open()) file_.close();
  10.     }
  11.     // 禁用拷贝,允许移动
  12.     SafeFile(const SafeFile&) = delete;
  13.     SafeFile& operator=(const SafeFile&) = delete;
  14.     SafeFile(SafeFile&&) = default;
  15.     SafeFile& operator=(SafeFile&&) = default;
  16.     void write(const std::string& data) {
  17.         file_ << data;
  18.         if (!file_.good()) throw std::runtime_error("写入失败");
  19.     }
  20. private:
  21.     std::ofstream file_;
  22. };
  23. // 使用示例
  24. void log_message(const std::string& msg) {
  25.     SafeFile logfile("app.log"); // RAII保证文件关闭
  26.     logfile.write(msg);
  27. }
复制代码

2. 非常安全的关键操纵

2.1 构造函数中的非常安全

  1. class DatabaseConnection {
  2. public:
  3.     DatabaseConnection(const std::string& config) {
  4.         handle_ = open_connection(config); // 可能失败的操作
  5.         if (!handle_) {
  6.             throw std::runtime_error("连接失败");
  7.         }
  8.         // 若此处抛出异常,已分配的handle_会被析构函数释放
  9.     }
  10.     ~DatabaseConnection() noexcept {
  11.         if (handle_) close_connection(handle_);
  12.     }
  13. private:
  14.     DBHandle* handle_ = nullptr;
  15. };
复制代码
2.2 赋值操纵符的非常安全

  1. class Config {
  2. public:
  3.     Config& operator=(const Config& other) {
  4.         if (this != &other) {
  5.             auto temp = other.data_;  // 先复制数据
  6.             data_.swap(temp);         // 无异常则交换(强保证)
  7.         }
  8.         return *this;
  9.     }
  10. private:
  11.     std::vector<std::string> data_;
  12. };
复制代码

3. 避免资源走漏的编码模式

3.1 确保先分配资源再修改状态

  1. void update_user_profile(User& user, const Profile& new_profile) {
  2.     auto* new_data = new ProfileData(new_profile); // 先分配资源
  3.     delete user.data_;      // 再释放旧资源
  4.     user.data_ = new_data;  // 最后更新指针
  5. }
复制代码
3.2 利用std::lock_guard管理互斥锁

  1. #include <mutex>
  2. std::mutex db_mutex;
  3. void thread_safe_query() {
  4.     std::lock_guard<std::mutex> lock(db_mutex); // 自动释放锁
  5.     execute_query("SELECT * FROM users");       // 可能抛出异常
  6. }
复制代码

4. 非常安全的数据结构操纵

4.1 利用std::vector取代裸数组

  1. class SensorData {
  2. public:
  3.     void add_reading(double value) {
  4.         readings_.push_back(value); // 可能抛出bad_alloc
  5.         // 若push_back失败,readings_仍保持原有数据
  6.     }
  7. private:
  8.     std::vector<double> readings_; // 自动管理内存
  9. };
复制代码
4.2 安全的元素删除(先复制后修改)

  1. void remove_invalid_entries(std::vector<Entry>& entries) {
  2.     auto valid_entries = entries; // 先创建副本
  3.     std::erase_if(valid_entries, [](const Entry& e) {
  4.         return !e.is_valid();
  5.     });
  6.     entries.swap(valid_entries);  // 无异常则原子交换
  7. }
复制代码

5. 测试非常安全

5.1 验证资源开释

  1. TEST_CASE("数据库连接异常时释放资源") {
  2.     bool resource_released = false;
  3.     try {
  4.         DatabaseConnection conn("invalid_config"); // 构造失败
  5.     } catch (...) {
  6.         resource_released = check_resource_cleanup(); // 验证句柄已关闭
  7.     }
  8.     REQUIRE(resource_released);
  9. }
复制代码
5.2 验证数据一致性

  1. TEST_CASE("vector插入失败时保持原数据") {
  2.     std::vector<int> data = {1, 2, 3};
  3.     auto original = data;
  4.     try {
  5.         data.insert(data.end(), 4); // 假设插入失败抛出异常
  6.     } catch (...) {
  7.         REQUIRE(data == original); // 数据未损坏
  8.     }
  9. }
复制代码

关键原则总结

原则实现方法示例资源主动开释利用RAII对象(智能指针、容器、自定义类)std::unique_ptr, SafeFile操纵序次安全先分配新资源,再开释旧资源new_data → delete old无副作用修改先操纵副本,成功后再修改主数据temp.swap(data_)原子性操纵利用swap或move实现无非常操纵vector::swap避免裸资源管理优先利用标准库容器而非new/deletestd::vector取代int[]
通过遵循这些实践,纵然代码中发生非常,也能确保:

  • 资源不走漏:所有已分配的内存、文件句柄、网络毗连等都会被正确开释
  • 对象有效:所有对象处于可安全析构的状态
  • 数据一致性:关键数据结构不会处于半完成状态
终极发起:在类的设计文档中明确标注每个方法的非常安全品级(基本/强/无非常),作为与团队约定的左券。
9 除非有足够的理由,否则最好提供强保障。

在C++中,强非常安全包管(Strong Exception Safety Guarantee) 要求操纵要么完全成功,要么失败时程序状态与操纵开始前完全一致。以下是如何实现这一目的的战略与代码示例:

1. 强非常安全的核心模式

1.1 Copy-and-Swap 模式

  1. class Config {
  2. public:
  3.     void update(const std::string& key, const std::string& value) {
  4.         auto temp = data_;      // 1. 创建副本
  5.         temp[key] = value;      // 2. 修改副本(可能抛异常)
  6.         data_.swap(temp);       // 3. 无异常则原子交换
  7.     }
  8. private:
  9.     std::map<std::string, std::string> data_;
  10. };
复制代码
1.2 事务性文件写入

  1. void safe_write_file(const std::string& path, const std::string& content) {
  2.     const std::string temp_path = path + ".tmp";
  3.    
  4.     { // 临时文件作用域
  5.         std::ofstream tmp(temp_path);
  6.         if (!tmp) throw FileOpenError(temp_path);
  7.         tmp << content; // 可能抛异常
  8.     } // 文件流在此析构,确保内容刷新到磁盘
  9.     if (std::rename(temp_path.c_str(), path.c_str()) != 0) {
  10.         throw FileRenameError(temp_path, path);
  11.     }
  12. }
复制代码

2. 标准库的强安全操纵

2.1 std::vector 的插入操纵

  1. std::vector<int> data = {1, 2, 3};
  2. // 强安全保证的插入方式
  3. data.reserve(data.size() + 1); // 预先分配空间(可能抛bad_alloc)
  4. data.push_back(4);             // 不会重新分配,保证强安全
复制代码
2.2 std::map 的安全更新

  1. std::map<int, std::string> registry;
  2. // 安全插入或更新
  3. auto hint = registry.find(42);
  4. if (hint != registry.end()) {
  5.     auto temp = hint->second;  // 创建副本
  6.     temp += "_modified";        // 修改副本
  7.     registry[42] = std::move(temp); // 原子替换
  8. } else {
  9.     registry.emplace(42, "new_value"); // 无副作用的插入
  10. }
复制代码

3. 移动语义优化

3.1 移动+回滚机制

  1. class Transaction {
  2. public:
  3.     Transaction() {
  4.         backup_ = current_state_; // 保存初始状态
  5.     }
  6.     void commit() {
  7.         // 尝试应用修改(可能抛异常)
  8.         apply_changes();
  9.         committed_ = true;
  10.     }
  11.     ~Transaction() {
  12.         if (!committed_) {
  13.             current_state_ = backup_; // 失败时回滚
  14.         }
  15.     }
  16. private:
  17.     static State current_state_;
  18.     State backup_;
  19.     bool committed_ = false;
  20. };
  21. // 使用示例
  22. void business_operation() {
  23.     Transaction tx;  // 进入作用域即开始事务
  24.     tx.modify_A();   // 修改操作
  25.     tx.modify_B();
  26.     tx.commit();     // 无异常则提交
  27. } // 析构时自动处理回滚
复制代码

4. 性能衡量场景

4.1 可担当的妥协示例

  1. // 场景:高频调用的低延迟函数
  2. void process_packet(NetworkPacket& packet) noexcept {
  3.     // 禁用异常,使用错误码返回
  4.     if (!validate(packet)) {
  5.         stats_.invalid_packets++; // 基本保证:计数器可能少计
  6.         return;
  7.     }
  8.     // 处理逻辑...
  9. }
复制代码
妥协理由


  • 每秒处置处罚百万级网络包
  • 错误率低于0.1%
  • 计数器精度损失可担当

5. 强安全测试战略

5.1 利用std::exception_ptr模仿失败

  1. TEST_CASE("数据库更新满足强安全保证") {
  2.     Database original = get_current_state();
  3.     bool exception_thrown = false;
  4.     try {
  5.         // 模拟可能失败的操作
  6.         throw_on_nth_call(2); // 第2次调用抛异常
  7.         perform_atomic_update();
  8.     } catch (...) {
  9.         exception_thrown = true;
  10.     }
  11.     REQUIRE(exception_thrown);
  12.     REQUIRE(get_current_state() == original); // 验证状态回滚
  13. }
复制代码

实现强安全的关键技术

技术适用场景示例Copy-and-Swap对象状态修改vector::push_back事务模式多步调操纵数据库事务无副操纵简朴查询/只读方法const成员函数移动语义资源所有权转移std::unique_ptr的移动构造延迟修改必要原子性的批量操纵先收集所有修改,最后一次性提交
何时可以放宽要求?

场景可担当的安全品级理由性能关键路径基本包管强安全开销凌驾性能预算临时对象操纵无包管对象即将销毁,状态无关紧要错误统计基本包管计数器误差可担当硬件交互无包管物理设备状态无法回滚
最佳实践总结


  • 默认选择强安全:除非有明确理由否则优先实现
  • 利用标准库办法:vector::push_back、map::emplace等
  • 事务封装:对复杂操纵利用RAII事务包装器
  • 移动优于拷贝:用移动语义减少临时对象创建
  • 明确文档左券:在函数注释中声明安全品级
通过遵循这些原则,可以在大多数场景下以公道成本实现强非常安全,构建出既健壮又高效的C++体系。
10 让构造函数建立不变式,假如不能,则抛出非常。

在C++中,构造函数是建立类不变式(class invariants)的理想位置。假如构造函数无法满意类的不变式要求,应当抛出非常以确保对象不会被部分构造或处于无效状态。以下是详细实现战略和代码示例:

1. 基本设计原则


  • 不变式定义:明确类在任何时间必须满意的条件(如0 < month <= 12)。
  • 构造函数验证:在构造函数中强制查抄不变式条件。
  • 非常抛出:若不变式无法建立,立即抛出非常制止对象创建。
  • 资源安全:利用RAII确保已分配资源在抛出非常前主动开释。

2. 标准示例:日期类

  1. #include <stdexcept>
  2. #include <string>
  3. class Date {
  4. public:
  5.     // 构造函数必须建立"有效日期"的不变式
  6.     Date(int year, int month, int day)
  7.         : year_(year), month_(month), day_(day)
  8.     {
  9.         if (!is_valid(year, month, day)) {
  10.             throw std::invalid_argument("无效的日期");
  11.         }
  12.     }
  13. private:
  14.     int year_, month_, day_;
  15.     static bool is_valid(int y, int m, int d) {
  16.         if (m < 1 || m > 12) return false;
  17.         if (d < 1 || d > days_in_month(y, m)) return false;
  18.         return true;
  19.     }
  20.     static int days_in_month(int y, int m) { /* ... */ }
  21. };
  22. // 使用示例
  23. try {
  24.     Date birthday(2023, 2, 30); // 抛出异常:2月无30日
  25. } catch (const std::invalid_argument& e) {
  26.     std::cerr << "错误: " << e.what() << std::endl;
  27. }
复制代码

3. 复杂场景:资源管理类

3.1 文件句柄管理

  1. #include <fstream>
  2. #include <memory>
  3. class SafeFile {
  4. public:
  5.     explicit SafeFile(const std::string& path)
  6.         : file_(std::make_unique<std::ifstream>(path))
  7.     {
  8.         if (!file_->is_open()) {
  9.             throw std::runtime_error("无法打开文件: " + path);
  10.         }
  11.         // 其他初始化(如读取文件头验证)
  12.         validate_header();
  13.     }
  14. private:
  15.     std::unique_ptr<std::ifstream> file_;
  16.     void validate_header() {
  17.         char header[4];
  18.         file_->read(header, 4);
  19.         if (!is_valid_header(header)) {
  20.             throw std::runtime_error("文件头不合法");
  21.         }
  22.     }
  23. };
  24. // 使用示例
  25. try {
  26.     SafeFile config("settings.dat"); // 可能抛出两种异常
  27. } catch (const std::exception& e) {
  28.     // 文件打开失败或头验证失败
  29. }
复制代码
3.2 数据库毗连池

  1. #include <vector>
  2. #include <memory>
  3. class DatabaseConnection { /* ... */ };
  4. class ConnectionPool {
  5. public:
  6.     ConnectionPool(size_t pool_size, const std::string& conn_str)
  7.         : connections_()
  8.     {
  9.         if (pool_size == 0) {
  10.             throw std::invalid_argument("连接池大小必须>0");
  11.         }
  12.         try {
  13.             for (size_t i = 0; i < pool_size; ++i) {
  14.                 connections_.push_back(
  15.                     std::make_unique<DatabaseConnection>(conn_str)
  16.                 );
  17.             }
  18.         } catch (const DatabaseException&) {
  19.             // 部分连接已创建,但构造函数失败
  20.             // unique_ptr自动释放已分配连接
  21.             throw; // 重新抛出
  22.         }
  23.     }
  24. private:
  25.     std::vector<std::unique_ptr<DatabaseConnection>> connections_;
  26. };
复制代码

4. 高级本领:复合对象构造

4.1 成员对象的非常安全初始化

  1. class UserProfile {
  2. public:
  3.     UserProfile(const std::string& name, int age)
  4.         : name_(validate_name(name)),  // 可能抛异常
  5.           age_(validate_age(age)),     // 可能抛异常
  6.           preferences_(load_prefs())   // 可能抛异常
  7.     {
  8.         // 所有成员已成功初始化才进入构造函数体
  9.     }
  10. private:
  11.     std::string name_;
  12.     int age_;
  13.     Preferences preferences_;
  14.     static std::string validate_name(const std::string& name) {
  15.         if (name.empty()) throw std::invalid_argument("名字不能为空");
  16.         return name;
  17.     }
  18.     static int validate_age(int age) {
  19.         if (age < 0) throw std::invalid_argument("年龄不能为负");
  20.         return age;
  21.     }
  22.     static Preferences load_prefs() { /* 可能抛异常 */ }
  23. };
复制代码

5. 错误处置处罚最佳实践

场景处置处罚战略代码示例参数无效抛出std::invalid_argumentthrow std::invalid_argument(...)资源分配失败抛出std::runtime_error或其派生类throw std::runtime_error(...)依赖项初始化失败答应非常流传,RAII主动清理不捕获,依赖析构函数开释资源多阶段验证在成员初始化列表中尽早失败: member(validate(arg))
关键原则总结


  • 失败前置:在构造函数体实验前验证参数(利用成员初始化列表)
  • 原子性构造:要么完全成功,要么抛出非常(无半构造对象)
  • 资源自治:每个成员自身管理资源(利用智能指针、容器等)
  • 非常类型明确:根据错误类型选择标准或自定义非常
  • 克制吞非常:构造函数不应捕获无关非常
通过遵循这些原则,可以确保类的实例始终处于有效状态,同时保持代码的健壮性和可维护性。
11 抛出非常前先开释局部资源。

在C++中,确保在抛出非常前开释局部资源的最佳实践是接纳RAII(Resource Acquisition Is Initialization)机制。以下是分步说明和代码示例:

1. 明白RAII原则



  • 核心思想:将资源(内存、文件句柄、锁等)的生命周期绑定到对象的生命周期。
  • 构造函数:获取资源。
  • 析构函数:开释资源,确保在对象销毁时主动开释。

2. 利用智能指针管理动态内存

示例:避免内存走漏

  1. #include <memory>
  2. #include <vector>
  3. void process_data() {
  4.     std::unique_ptr<std::vector<int>> data = std::make_unique<std::vector<int>>(1000);
  5.     // 操作数据,可能抛出异常
  6.     data->push_back(42);
  7.     // 无需手动释放内存,unique_ptr析构时自动释放
  8. }
复制代码

3. 封装文件句柄的RAII类

示例:安全处置处罚文件

  1. #include <cstdio>
  2. class FileRAII {
  3. public:
  4.     FileRAII(const char* filename, const char* mode) : file_(fopen(filename, mode)) {
  5.         if (!file_) throw std::runtime_error("无法打开文件");
  6.     }
  7.     ~FileRAII() noexcept {
  8.         if (file_) fclose(file_);
  9.     }
  10.     FILE* handle() const { return file_; }
  11.     // 禁用拷贝
  12.     FileRAII(const FileRAII&) = delete;
  13.     FileRAII& operator=(const FileRAII&) = delete;
  14. private:
  15.     FILE* file_;
  16. };
  17. void read_file() {
  18.     FileRAII file("data.txt", "r"); // 文件打开成功
  19.     // 读取文件操作,若抛出异常,析构函数自动关闭文件
  20.     char buffer[1024];
  21.     fread(buffer, 1, sizeof(buffer), file.handle());
  22. }
复制代码

4. 利用标准库容器管理资源

示例:主动开释动态数组

  1. #include <vector>
  2. void safe_array_operation() {
  3.     std::vector<int> array(1000); // 自动管理内存
  4.     array[0] = 42;               // 操作可能抛出异常
  5.     // 无需手动释放,vector析构时自动释放内存
  6. }
复制代码

5. 锁管理的RAII实现

示例:避免死锁

  1. #include <mutex>
  2. std::mutex critical_section_mutex;
  3. void thread_safe_operation() {
  4.     std::lock_guard<std::mutex> lock(critical_section_mutex); // 自动加锁
  5.     // 临界区操作,可能抛出异常
  6.     // 析构时自动解锁,即使发生异常
  7. }
复制代码

6. 自定义数据库毗连的RAII类

示例:安全开释数据库毗连

  1. class DatabaseConnection {
  2. public:
  3.     DatabaseConnection(const std::string& conn_str) {
  4.         connect(conn_str); // 可能抛出连接异常
  5.     }
  6.     ~DatabaseConnection() noexcept {
  7.         if (connected_) disconnect(); // 确保关闭连接
  8.     }
  9.     void query(const std::string& sql) { /* 可能抛出查询异常 */ }
  10. private:
  11.     bool connected_ = false;
  12.     void connect(const std::string& str) { /* ... */ }
  13.     void disconnect() noexcept { /* ... */ }
  14. };
  15. void use_database() {
  16.     DatabaseConnection db("user=admin;password=1234"); // 连接成功
  17.     db.query("SELECT * FROM users");                   // 可能抛出异常
  18.     // 析构时自动断开连接
  19. }
复制代码

7. 手动资源管理的正确方式(不推荐)

示例:在try块内开释资源

  1. void legacy_code() {
  2.     Resource* res = acquire_resource(); // 获取资源
  3.     try {
  4.         use_resource(res); // 可能抛出异常
  5.     } catch (...) {
  6.         release_resource(res); // 异常时释放资源
  7.         throw;                // 重新抛出
  8.     }
  9.     release_resource(res); // 正常流程释放
  10. }
复制代码

关键原则总结

场景RAII解决方案上风动态内存std::unique_ptr, std::vector主动开释内存,避免走漏文件操纵自定义FileRAII类或std::fstream非常安全地关闭文件句柄多线程锁std::lock_guard主动解锁,防止死锁网络/数据库毗连封装毗连的RAII类确保毗连终极关闭第三方C库资源自定义RAII包装器将C风格资源转换为非常安全对象
为何RAII优于手动开释?


  • 非常安全:纵然抛出非常,析构函数仍会调用。
  • 代码简便:消除重复的try-catch和delete/free调用。
  • 维护性强:资源生命周期清晰可见。
  • 性能优化:减少冗余错误查抄代码。

验证RAII的非常安全性

  1. #include <cassert>
  2. class TestRAII {
  3. public:
  4.     TestRAII(bool fail) : valid_(true) {
  5.         if (fail) throw std::runtime_error("构造失败");
  6.     }
  7.     ~TestRAII() { valid_ = false; }
  8.     bool is_valid() const { return valid_; }
  9. private:
  10.     bool valid_;
  11. };
  12. int main() {
  13.     try {
  14.         TestRAII obj(true); // 构造时抛出异常
  15.     } catch (const std::exception&) {
  16.         // 对象未被完全构造,析构函数不会执行
  17.     }
  18.     TestRAII normal_obj(false);
  19.     assert(normal_obj.is_valid()); // 正常构造
  20.     return 0; // 析构函数调用,valid_变为false
  21. }
复制代码

通过遵循RAII原则,您可以确保所有局部资源在非常发生时被正确开释,从而编写出健壮且易于维护的C++代码。
12 服膺在构造函数中抛出非常前开释所有已获取的资源。

在C++中,当构造函数抛出非常时,已完全构造的成员变量和基类子对象的析构函数会被调用,但当前对象的析构函数不会实验。因此,必须通过RAII机制确保资源主动开释。以下是关键原则和代码示例:

1. 基本原则:分层获取资源

1.1 成员变量按声明序次初始化

  1. class DatabaseConnection {
  2. public:
  3.     // RAII成员按声明顺序初始化
  4.     DatabaseConnection(const std::string& conn_str)
  5.         : logger_("db.log"),      // 1. 先初始化日志文件(RAII)
  6.           handle_(connect(conn_str)) // 2. 再获取数据库连接
  7.     {
  8.         if (!handle_) {
  9.             // ❌ 错误:此时logger_已初始化,无法阻止其析构函数调用
  10.             throw std::runtime_error("连接失败");
  11.         }
  12.     }
  13. private:
  14.     FileRAII logger_;  // RAII成员,自动管理文件资源
  15.     DBHandle* handle_; // ❌ 危险:裸指针需手动释放
  16. };
复制代码
修正方案:所有资源由RAII成员管理

  1. class DatabaseConnection {
  2. public:
  3.     DatabaseConnection(const std::string& conn_str)
  4.         : logger_("db.log"),
  5.           handle_(make_connection(conn_str)) // handle_是unique_ptr
  6.     {
  7.         if (!handle_) {
  8.             // ✅ 无需手动释放,handle_析构函数自动处理
  9.             throw std::runtime_error("连接失败");
  10.         }
  11.     }
  12. private:
  13.     FileRAII logger_;
  14.     std::unique_ptr<DBHandle> handle_; // RAII管理数据库连接
  15. };
复制代码

2. 分步资源获取战略

2.1 每个资源对应一个RAII成员

  1. class SecureSession {
  2. public:
  3.     SecureSession(const std::string& user)
  4.         : auth_token_(authenticate(user)), // RAII成员1:令牌
  5.           encryptor_(init_encryption()),  // RAII成员2:加密器
  6.           log_stream_("session.log")      // RAII成员3:日志文件
  7.     {
  8.         // 所有资源通过成员初始化列表获取
  9.         // 任一成员构造失败都会导致已构造成员的析构
  10.     }
  11. private:
  12.     AuthTokenRAII auth_token_;
  13.     EncryptionRAII encryptor_;
  14.     FileRAII log_stream_;
  15. };
复制代码
2.2 动态资源管理

  1. class ImageProcessor {
  2. public:
  3.     ImageProcessor(int width, int height)
  4.         : buffer1_(std::make_unique<uint8_t[]>(width * height)),
  5.           buffer2_(std::make_unique<uint8_t[]>(width * height))
  6.     {
  7.         if (!validate_buffers()) {
  8.             throw std::runtime_error("缓冲区初始化失败");
  9.         }
  10.         // ✅ 异常安全:unique_ptr自动释放内存
  11.     }
  12. private:
  13.     std::unique_ptr<uint8_t[]> buffer1_;
  14.     std::unique_ptr<uint8_t[]> buffer2_;
  15. };
复制代码

3. 非常安全构造函数模板

3.1 正确模式

  1. class SafeResourceOwner {
  2. public:
  3.     SafeResourceOwner()
  4.         : res1_(acquire_resource_1()),  // RAII成员1
  5.           res2_(acquire_resource_2())   // RAII成员2
  6.     {
  7.         // 仅在所有资源就绪后进行额外操作
  8.         perform_initialization();
  9.     }
  10. private:
  11.     ResourceRAII res1_;
  12.     ResourceRAII res2_;
  13. };
复制代码
3.2 错误模式(手动管理)

  1. class DangerousResourceOwner {
  2. public:
  3.     DangerousResourceOwner() {
  4.         res1_ = new Resource(); // ❌ 裸指针
  5.         if (!res1_->ok()) {
  6.             delete res1_; // ⚠️ 必须手动释放
  7.             throw std::runtime_error("资源1失败");
  8.         }
  9.         res2_ = new Resource(); // ❌ 第二个资源
  10.         if (!res2_->ok()) {
  11.             delete res1_; // ⚠️ 需要手动释放res1_
  12.             delete res2_;
  13.             throw std::runtime_error("资源2失败");
  14.         }
  15.     }
  16.     ~DangerousResourceOwner() {
  17.         delete res1_;
  18.         delete res2_;
  19.     }
  20. private:
  21.     Resource* res1_;
  22.     Resource* res2_;
  23. };
复制代码

4. 无法利用RAII时的处置处罚

4.1 手动清理(不推荐,应急用)

  1. class LegacyWrapper {
  2. public:
  3.     LegacyWrapper() {
  4.         handle1_ = legacy_init_1(); // C风格API
  5.         if (!handle1_) {
  6.             legacy_cleanup_1(handle1_); // 手动清理
  7.             throw std::runtime_error("初始化1失败");
  8.         }
  9.         handle2_ = legacy_init_2();
  10.         if (!handle2_) {
  11.             legacy_cleanup_1(handle1_); // 清理已分配资源
  12.             legacy_cleanup_2(handle2_);
  13.             throw std::runtime_error("初始化2失败");
  14.         }
  15.     }
  16.     ~LegacyWrapper() {
  17.         legacy_cleanup_2(handle2_);
  18.         legacy_cleanup_1(handle1_);
  19.     }
  20. private:
  21.     LegacyHandle handle1_;
  22.     LegacyHandle handle2_;
  23. };
复制代码

关键原则总结

场景正确做法错误做法成员资源初始化通过RAII成员在初始化列表中获取资源在构造函数体内用new分配多资源依赖每个资源对应一个RAII成员,按依赖序次声明手动管理多个资源的开释序次第三方库集成编写RAII包装类封装C风格资源直接利用裸指针或句柄非常处置处罚依赖析构函数主动清理try-catch块内手动delete
验证工具

  1. // 使用valgrind检测资源泄漏
  2. valgrind --leak-check=full ./your_program
  3. // 编译时开启额外警告
  4. g++ -Wall -Wextra -Werror your_code.cpp
复制代码
通过严格遵循RAII原则,可以确保纵然构造函数抛出非常,所有已获取的资源也能被安全开释,避免内存走漏和资源滞留。
13 假如局部控制结构足以满意要求,不要利用非常。

在C++中,非常机制应仅用于处置处罚 不可规复的错误跨多层调用传递错误。对于可通过局部逻辑处置处罚的常规错误,优先利用控制结构(如if-else、while)而非非常。以下是详细场景和最佳实践:

1. 优先利用控制结构的场景

1.1 参数校验(可预期错误)

  1. // ✅ 正确:使用if直接处理
  2. std::optional<int> safe_divide(int a, int b) {
  3.     if (b == 0) return std::nullopt; // 预期内的错误
  4.     return a / b;
  5. }
  6. // ❌ 错误:滥用异常
  7. int unsafe_divide(int a, int b) {
  8.     if (b == 0) throw std::invalid_argument("除零错误");
  9.     return a / b;
  10. }
复制代码
1.2 用户输入验证

  1. // ✅ 正确:通过循环和条件重试
  2. int read_positive_number() {
  3.     int num;
  4.     while (true) {
  5.         std::cout << "输入正整数: ";
  6.         if (std::cin >> num && num > 0) return num;
  7.         std::cin.clear();
  8.         std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  9.         std::cout << "输入无效,请重试\n";
  10.     }
  11. }
  12. // ❌ 错误:输入错误时抛出异常(过度设计)
  13. int bad_read_number() {
  14.     int num;
  15.     if (!(std::cin >> num)) throw std::runtime_error("输入错误");
  16.     return num;
  17. }
复制代码

2. 错误码与状态标记

2.1 返回错误码

  1. enum class ErrorCode { Success, FileNotFound, InvalidData };
  2. ErrorCode process_file(const std::string& path) {
  3.     if (!file_exists(path)) return ErrorCode::FileNotFound;
  4.     // 处理文件内容...
  5.     return ErrorCode::Success;
  6. }
  7. // 调用方处理
  8. if (auto code = process_file("data.txt"); code != ErrorCode::Success) {
  9.     log_error(code);
  10. }
复制代码
2.2 利用std::expected(C++23)

  1. #include <expected>
  2. std::expected<std::string, ErrorCode> load_config(const std::string& path) {
  3.     if (!file_exists(path)) return std::unexpected(ErrorCode::FileNotFound);
  4.     // 读取配置...
  5.     return config_data;
  6. }
  7. // 调用方
  8. if (auto config = load_config("app.cfg"); config) {
  9.     use_config(*config);
  10. } else {
  11.     handle_error(config.error());
  12. }
复制代码

3. 资源管理(无需非常)

3.1 RAII主动开释

  1. class FileHandler {
  2. public:
  3.     FileHandler(const std::string& path) : file_(fopen(path.c_str(), "r")) {
  4.         if (!file_) log_error("打开文件失败"); // 记录但不抛异常
  5.     }
  6.     ~FileHandler() { if (file_) fclose(file_); }
  7.    
  8.     explicit operator bool() const { return file_ != nullptr; }
  9. private:
  10.     FILE* file_;
  11. };
  12. void process() {
  13.     FileHandler file("data.txt");
  14.     if (!file) return; // 提前退出
  15.     // 使用文件...
  16. }
复制代码

4. 性能敏感场景

4.1 高频调用函数

  1. // ✅ 正确:避免异常开销
  2. bool validate_packet(const Packet& pkt) {
  3.     if (pkt.size > MAX_SIZE) return false;
  4.     if (pkt.checksum != calculate_checksum(pkt)) return false;
  5.     return true;
  6. }
  7. // ❌ 错误:异常不适用于高频路径
  8. void bad_validate(const Packet& pkt) {
  9.     if (pkt.size > MAX_SIZE) throw InvalidPacket();
  10.     if (pkt.checksum != calculate_checksum(pkt)) throw InvalidPacket();
  11. }
复制代码

5. 替代非常的常用模式

场景替代方案工具/本领可规复错误返回错误码或bool状态std:ptional, std::expected可选值缺失std:ptional<T>C++17标准库多错误类型std::variant<T, Error>C++17联合类型输入验证循环+条件重试while + std::cin.fail()资源不可用RAII类+状态查抄自定义资源管理类
何时应利用非常?

场景示例理由内存耗尽new失败程序无法继承运行硬件故障磁盘写入失败无法通过局部逻辑规复第三方库瓦解数据库毗连突然断开跨层级错误传递不可规复的逻辑错误程序不变量被粉碎必要立即终止或重启
代码可维护性对比

非常滥用代码

  1. try {
  2.     auto data = parse_input();
  3.     save_to_db(data);
  4. } catch (const InvalidInput&) {
  5.     log("输入错误");
  6. } catch (const DatabaseTimeout&) {
  7.     retry();
  8. } catch (...) {
  9.     log("未知错误");
  10. }
复制代码
控制结构优化代码

  1. if (auto input = read_input(); input.valid()) {
  2.     if (auto conn = db.connect(); conn.active()) {
  3.         conn.save(input.data());
  4.     } else {
  5.         handle_db_error(conn.status());
  6.     }
  7. } else {
  8.     ask_for_retry();
  9. }
复制代码

总结:选择错误处置处罚战略的决议树

  1. 错误是否可预期且频繁发生?
  2. ├── 是 → 使用控制结构(if/返回码)
  3. └── 否 → 错误是否会导致程序无法继续?
  4.     ├── 是 → 抛出异常
  5.     └── 否 → 错误是否需要跨多层传递?
  6.         ├── 是 → 使用异常
  7.         └── 否 → 使用局部处理
复制代码
通过公道选择错误处置处罚战略,可明显提升代码性能和可维护性。记住:非常应作为“最后防线”,而非常规控制流工具
14 用“资源获取即初始化”技术管理资源。

在C++中,“资源获取即初始化”(RAII, Resource Acquisition Is Initialization)是管理资源的黄金准则。以下是分步调的详细说明和代码示例:

1. RAII核心思想

资源生命周期对象生命周期 绑定:


  • 构造函数:获取资源
  • 析构函数:开释资源
  • 无论程序流程如何(包罗非常),资源都能主动开释

2. 基本实现模板

  1. class RAIIWrapper {
  2. public:
  3.     // 构造函数获取资源
  4.     explicit RAIIWrapper(ResourceParams params)
  5.         : resource_(acquire_resource(params))
  6.     {
  7.         if (!resource_) throw ResourceAcquisitionFailed();
  8.     }
  9.     // 析构函数释放资源
  10.     ~RAIIWrapper() noexcept {
  11.         if (resource_) release_resource(resource_);
  12.     }
  13.     // 禁用拷贝(根据需要实现移动语义)
  14.     RAIIWrapper(const RAIIWrapper&) = delete;
  15.     RAIIWrapper& operator=(const RAIIWrapper&) = delete;
  16.     // 可选:提供资源访问接口
  17.     ResourceHandle get() const noexcept { return resource_; }
  18. private:
  19.     ResourceHandle resource_; // 资源句柄(指针、文件描述符等)
  20. };
复制代码

3. 范例应用场景

3.1 管理动态内存

  1. // 使用标准库智能指针(无需自定义)
  2. void process_data(size_t size) {
  3.     auto buffer = std::make_unique<int[]>(size); // RAII自动管理
  4.     // 使用buffer...
  5.     // 无需手动delete,离开作用域自动释放
  6. }
复制代码
3.2 管理文件句柄

  1. class FileRAII {
  2. public:
  3.     explicit FileRAII(const std::string& path, const char* mode = "r")
  4.         : file_(fopen(path.c_str(), mode))
  5.     {
  6.         if (!file_) throw std::runtime_error("无法打开文件");
  7.     }
  8.     ~FileRAII() noexcept {
  9.         if (file_) fclose(file_);
  10.     }
  11.     FILE* handle() const noexcept { return file_; }
  12.     // 启用移动语义
  13.     FileRAII(FileRAII&& other) noexcept
  14.         : file_(std::exchange(other.file_, nullptr)) {}
  15.    
  16.     FileRAII& operator=(FileRAII&& other) noexcept {
  17.         if (this != &other) {
  18.             if (file_) fclose(file_);
  19.             file_ = std::exchange(other.file_, nullptr);
  20.         }
  21.         return *this;
  22.     }
  23. private:
  24.     FILE* file_;
  25. };
  26. // 使用示例
  27. void read_file() {
  28.     FileRAII file("data.txt");
  29.     char buffer[1024];
  30.     fread(buffer, 1, sizeof(buffer), file.handle());
  31.     // 文件自动关闭
  32. }
复制代码
3.3 管理互斥锁

  1. #include <mutex>
  2. class CriticalSection {
  3. public:
  4.     void safe_operation() {
  5.         std::lock_guard<std::mutex> lock(mutex_); // RAII自动加锁
  6.         // 临界区操作...
  7.         // 离开作用域自动解锁
  8.     }
  9. private:
  10.     std::mutex mutex_;
  11. };
复制代码

4. 高级应用本领

4.1 延迟初始化

  1. class LazyResource {
  2. public:
  3.     void initialize() {
  4.         if (!resource_) {
  5.             resource_ = acquire_resource();
  6.             if (!resource_) throw std::bad_alloc();
  7.         }
  8.     }
  9.     ~LazyResource() {
  10.         if (resource_) release_resource(resource_);
  11.     }
  12. private:
  13.     ResourceHandle resource_ = nullptr;
  14. };
复制代码
4.2 组合RAII对象

  1. class DatabaseTransaction {
  2. public:
  3.     DatabaseTransaction(Database& db)
  4.         : conn_(db.acquire_connection()), // RAII成员1:连接
  5.           lock_(conn_.mutex())            // RAII成员2:锁
  6.     {
  7.         conn_.begin_transaction();
  8.     }
  9.     ~DatabaseTransaction() {
  10.         if (std::uncaught_exceptions() > 0) {
  11.             conn_.rollback();
  12.         } else {
  13.             conn_.commit();
  14.         }
  15.     }
  16. private:
  17.     DatabaseConnectionRAII conn_;
  18.     std::lock_guard<std::mutex> lock_;
  19. };
复制代码

5. 标准库RAII工具

资源类型标准库工具头文件动态内存std::unique_ptr, std::shared_ptr<memory>文件流std::fstream, std:fstream<fstream>互斥锁std::lock_guard, std::unique_lock<mutex>线程std::jthread (C++20)<thread>临时文件/目录std::filesystem::directory_entry<filesystem>
6. 非常安全包管

品级形貌实现方法基本包管资源不走漏,对象状态有效析构函数正确开释资源强包管操纵要么完全成功,要么无影响Copy-and-Swap + RAII无抛出包管操纵不会抛出非常noexcept + 简朴操纵
7. 验证RAII正确性

  1. // 测试用例:验证资源释放
  2. TEST_CASE("FileRAII自动关闭文件") {
  3.     FILE* raw_handle = nullptr;
  4.     {
  5.         FileRAII file("test.txt", "w");
  6.         raw_handle = file.handle();
  7.         REQUIRE(fileno(raw_handle) != -1); // 文件已打开
  8.     } // RAII对象析构
  9.     REQUIRE(fclose(raw_handle) == EOF); // 文件已关闭,再次关闭失败
  10. }
复制代码

总结

通过RAII技术:

  • 消除手动资源管理:避免new/delete、open/close的配对问题
  • 包管非常安全:纵然发生非常,资源也能正确开释
  • 提升代码可读性:资源生命周期清晰可见
  • 支持更复杂的资源战略:通过组合RAII对象实现事务操纵
发起将RAII作为C++资源管理的默认方式,仅在极少数必要手动控制的场景(如性能关键路径)才思量其他方案。
15 尽量减少利用try块。

在C++中,资源获取即初始化(RAII) 是管理资源(如内存、文件句柄、网络毗连等)的核心技术,通过将资源生命周期与对象生命周期绑定,确保资源主动开释。以下是详细实现战略和代码示例:

1. RAII 核心原则



  • 构造函数获取资源:资源在对象构造时初始化。
  • 析构函数开释资源:对象销毁时主动开释资源。
  • 非常安全:纵然程序抛出非常,资源也能正确开释。

2. 底子模板:自定义RAII类

2.1 管理文件句柄

  1. #include <cstdio>
  2. class FileRAII {
  3. public:
  4.     // 构造函数打开文件
  5.     explicit FileRAII(const char* path, const char* mode = "r")
  6.         : file_(fopen(path, mode)) {
  7.         if (!file_) throw std::runtime_error("无法打开文件");
  8.     }
  9.     // 析构函数关闭文件
  10.     ~FileRAII() noexcept {
  11.         if (file_) fclose(file_);
  12.     }
  13.     // 禁用拷贝,允许移动
  14.     FileRAII(const FileRAII&) = delete;
  15.     FileRAII& operator=(const FileRAII&) = delete;
  16.     FileRAII(FileRAII&& other) noexcept : file_(other.file_) {
  17.         other.file_ = nullptr;
  18.     }
  19.     // 提供资源访问接口
  20.     FILE* handle() const noexcept { return file_; }
  21. private:
  22.     FILE* file_;
  23. };
  24. // 使用示例
  25. void read_file() {
  26.     FileRAII file("data.txt"); // 打开文件
  27.     char buffer[1024];
  28.     fread(buffer, 1, sizeof(buffer), file.handle());
  29.     // 离开作用域时,file析构自动关闭文件
  30. }
复制代码
2.2 管理动态数组

  1. template <typename T>
  2. class DynamicArrayRAII {
  3. public:
  4.     explicit DynamicArrayRAII(size_t size)
  5.         : data_(new T[size]), size_(size) {}
  6.    
  7.     ~DynamicArrayRAII() noexcept { delete[] data_; }
  8.     T& operator[](size_t index) { return data_[index]; }
  9. private:
  10.     T* data_;
  11.     size_t size_;
  12. };
  13. // 使用示例
  14. void process_data() {
  15.     DynamicArrayRAII<int> arr(1000); // 分配内存
  16.     arr[0] = 42;
  17.     // 离开作用域时内存自动释放
  18. }
复制代码

3. 标准库RAII工具

3.1 智能指针管理内存

  1. #include <memory>
  2. void safe_memory_management() {
  3.     auto ptr = std::make_unique<int[]>(1000); // unique_ptr自动释放
  4.     auto shared = std::make_shared<Resource>(); // shared_ptr引用计数
  5. }
复制代码
3.2 互斥锁管理(多线程安全)

  1. #include <mutex>
  2. class ThreadSafeCounter {
  3. public:
  4.     void increment() {
  5.         std::lock_guard<std::mutex> lock(mutex_); // 自动加锁/解锁
  6.         ++count_;
  7.     }
  8. private:
  9.     int count_ = 0;
  10.     std::mutex mutex_;
  11. };
复制代码

4. 高级应用场景

4.1 管理数据库毗连

  1. class DatabaseSession {
  2. public:
  3.     explicit DatabaseSession(const std::string& conn_str) {
  4.         session_ = connect(conn_str); // 可能抛异常
  5.         if (!session_.active()) throw std::runtime_error("连接失败");
  6.     }
  7.     ~DatabaseSession() {
  8.         if (session_.active()) disconnect(session_);
  9.     }
  10.     void query(const std::string& sql) { /* ... */ }
  11. private:
  12.     DatabaseHandle session_;
  13. };
  14. // 使用示例
  15. void run_query() {
  16.     DatabaseSession db("user=admin;password=1234");
  17.     db.query("SELECT * FROM users");
  18.     // 离开作用域时自动断开连接
  19. }
复制代码
4.2 组合RAII对象(事务操纵)

  1. class Transaction {
  2. public:
  3.     Transaction(Database& db)
  4.         : conn_(db.acquire_connection()), // RAII成员1:连接
  5.           lock_(conn_.mutex())            // RAII成员2:锁
  6.     {
  7.         conn_.begin();
  8.     }
  9.     ~Transaction() {
  10.         if (std::uncaught_exceptions() > 0) conn_.rollback();
  11.         else conn_.commit();
  12.     }
  13. private:
  14.     DatabaseConnectionRAII conn_;
  15.     std::lock_guard<std::mutex> lock_;
  16. };
复制代码

5. RAII设计原则

原则实现方式示例资源获取即初始化构造函数中获取资源FileRAII构造函数打开文件资源开释即析构析构函数中开释资源(标记为noexcept)~FileRAII()关闭文件禁用拷贝,支持移动删除拷贝构造函数,实现移动语义FileRAII(FileRAII&&)非常安全构造函数失败时抛出非常,析构函数确保开释资源构造函数中throw,析构中fclose提供访问接口通过成员函数暴露资源handle()返回文件指针
6. 常见问题解决

6.1 构造函数中部分资源初始化失败

  1. class MultiResource {
  2. public:
  3.     MultiResource()
  4.         : res1_(acquire_resource_1()), // 若此处失败,无资源需释放
  5.           res2_(acquire_resource_2())  // 若此处失败,res1_的析构函数自动释放
  6.     {}
  7. private:
  8.     ResourceRAII res1_;
  9.     ResourceRAII res2_;
  10. };
复制代码
6.2 延迟资源初始化

  1. class LazyResource {
  2. public:
  3.     void initialize() {
  4.         if (!resource_) {
  5.             resource_ = acquire_resource(); // 延迟获取资源
  6.             if (!resource_) throw std::bad_alloc();
  7.         }
  8.     }
  9.     ~LazyResource() { if (resource_) release_resource(resource_); }
  10. private:
  11.     ResourceHandle resource_ = nullptr;
  12. };
复制代码

7. RAII与非常安全品级

安全品级形貌RAII实现方式基本非常安全资源不走漏,对象状态有效析构函数正确开释资源强非常安全操纵要么完全成功,要么无副作用Copy-and-Swap + RAII成员无抛出包管操纵绝不抛非常noexcept + 简朴操纵
总结

通过RAII技术,可以:

  • 消除手动资源管理:避免new/delete、open/close的配对错误。
  • 包管非常安全:纵然发生非常,资源也能正确开释。
  • 提升代码可读性:资源生命周期与对象作用域一致。
  • 支持复杂资源战略:通过组合RAII对象实现事务、延迟初始化等高级功能。
推荐实践


  • 优先利用标准库RAII工具(如智能指针、lock_guard)。
  • 对第三方库资源(如OpenGL纹理、数据库毗连)封装自定义RAII类。
  • 在构造函数中完成所有资源初始化,避免部分初始化状态。
16 并非所有程序都必要非常安全。

在C++开发中,确实存在不必要追求非常安全性的场景。以下是分层说明和详细实践指南:

一、不必要非常安全的范例场景

1. 性能敏感型代码

  1. // 高频交易系统的核心循环
  2. void process_market_data(Packet& pkt) noexcept {
  3.     if (pkt.size != VALID_SIZE) return;  // 直接返回错误码
  4.     calculate_indicators(pkt.data);     // 禁用异常开销
  5.     send_to_engine(pkt);                // 要求绝对低延迟
  6. }
复制代码
特点


  • 利用noexcept标记函数
  • 错误处置处罚通过返回值或状态位完成
  • 牺牲错误信息丰富性换取纳秒级性能

2. 嵌入式及时体系

  1. // 电机控制固件
  2. void control_motor(RPM target) {
  3.     uint16_t current = read_sensor();  // 无异常支持的硬件操作
  4.     if (current > MAX_SAFE_VALUE) {
  5.         emergency_shutdown();          // 直接终止异常状态
  6.         return ERROR_CODE;
  7.     }
  8.     adjust_pwm(target);               // 确定性时序要求
  9. }
复制代码
特点


  • 编译器禁用非常(-fno-exceptions)
  • 通过LED闪耀或看门狗复位处置处罚严重错误
  • 错误处置处罚路径必须包管在微秒级完成

3. 简朴下令行工具

  1. // 一次性数据处理工具
  2. int main(int argc, char** argv) {
  3.     if (argc < 2) {
  4.         fprintf(stderr, "Usage: %s <file>\n", argv[0]);
  5.         return EXIT_FAILURE;  // 直接退出无需恢复状态
  6.     }
  7.     process_file(argv[1]);    // 单次执行无需回滚
  8. }
复制代码
特点


  • 错误直接导致程序终止
  • 无恒久运行状态必要维护
  • 资源管理依赖操纵体系主动接纳

二、非非常安全代码编写规范

1. 资源管理战略

  1. // C风格手动管理(需严格配对)
  2. void legacy_image_processing() {
  3.     uint8_t* buffer = malloc(1024*1024);
  4.     if (!buffer) return;
  5.     FILE* fp = fopen("data.raw", "rb");
  6.     if (!fp) {
  7.         free(buffer);  // 必须手动释放
  8.         return;
  9.     }
  10.     process(buffer, fp);
  11.     fclose(fp);
  12.     free(buffer);
  13. }
复制代码
要点


  • 每个malloc必须有对应的free
  • 每个open必须有对应的close
  • 错误路径需手工回滚资源分配

2. 错误码传递规范

  1. enum Error { SUCCESS, FILE_ERROR, NETWORK_ERROR };
  2. Error download_file(const char* url) {
  3.     CURL* curl = curl_easy_init();
  4.     if (!curl) return NETWORK_ERROR;
  5.     FILE* fp = fopen("temp.tmp", "wb");
  6.     if (!fp) {
  7.         curl_easy_cleanup(curl);  // 手动清理
  8.         return FILE_ERROR;
  9.     }
  10.     //...传输操作...
  11.    
  12.     fclose(fp);
  13.     curl_easy_cleanup(curl);
  14.     return SUCCESS;
  15. }
复制代码
要点


  • 定义清晰的错误码罗列
  • 每个函数必须返回实验状态
  • 调用方需查抄所有返回值

3. 断言辅助调试

  1. // 快速失败策略用于开发阶段
  2. void unsafe_optimization(float* data) {
  3.     assert(data != nullptr && "空指针传递给算法核心");  // 调试期检查
  4.     simd_processing(data);  // Release模式可能产生未定义行为
  5. }
复制代码
特点


  • NDEBUG发布版主动移除查抄
  • 仅用于捕捉开发阶段明显错误
  • 不处置处罚运行时不可猜测错误

三、非常安全与RAII的替代方案

1. 作用域退出主动实验

  1. #include <experimental/scope>
  2. void modern_without_exceptions() {
  3.     FILE* fp = fopen("data.txt", "r");
  4.     auto file_guard = std::experimental::make_scope_exit([&]{
  5.         if (fp) fclose(fp);
  6.     });
  7.     process_content(fp);  // 无论是否出错都会关闭文件
  8. }
复制代码
上风


  • 类似RAII的局部资源管理
  • 无需定义完整包装类
  • 支持C风格资源管理

2. 状态标记对象

  1. class NetworkController {
  2. public:
  3.     bool connect(const std::string& ip) {
  4.         if (!hardware_ready_) return false;  // 状态检查
  5.         //...物理层操作...
  6.         return true;
  7.     }
  8.     void disconnect() noexcept {
  9.         if (connected_) release_port();
  10.     }
  11. private:
  12.     bool hardware_ready_ = false;
  13.     bool connected_ = false;
  14. };
复制代码
上风


  • 对象始终保持有效状态
  • 方法返回操纵是否成功
  • 析构函数包管底子清理

四、禁用非常的工程配置

1. 编译器参数设置

  1. # GCC/Clang禁用异常
  2. g++ -fno-exceptions -stdlib=libc++ app.cpp
  3. # MSVC禁用异常(需配合宏)
  4. cl /EHsc- app.cpp
复制代码
2. 标准库举动调解

  1. // 重载operator new为不抛出版本
  2. void* operator new(size_t size) {
  3.     if (auto ptr = malloc(size)) return ptr;
  4.     std::abort();  // 内存耗尽直接终止
  5. }
  6. // 使用无异常容器
  7. std::vector<int, non_throw_allocator<int>> safe_vec;
复制代码

五、决议流程图

     
总结

当开发一次性工具、及时体系、性能关键型组件时,可放弃非常安全机制,通过:

  • 严格配对手工资源管理
  • 清晰错误码传递体系
  • 断言辅助调试
  • 作用域保卫工具
    来构建可靠体系。但需在项目文档中明确标注非非常安全模块,限定其利用范围。
17 用“资源获取即初始化”技术和非常处置处罚程序维护不变式。

在C++中,通过 资源获取即初始化(RAII) 结合 非常处置处罚,可以有效地维护类的不变式(Class Invariants),确保对象始终处于有效状态。以下是详细实现战略和代码示例:

1. 核心原则



  • 构造函数建立不变式:若无法满意不变式,立即抛出非常。
  • 析构函数开释资源:确保对象销毁时清理资源。
  • 成员变量RAII化:所有资源由RAII对象管理,避免手动清理。

2. 底子示例:文件管理类

  1. #include <fstream>
  2. #include <stdexcept>
  3. class SafeFile {
  4. public:
  5.     // 构造函数:尝试打开文件,失败则抛出异常
  6.     explicit SafeFile(const std::string& path)
  7.         : file_(path, std::ios::binary)
  8.     {
  9.         if (!file_.is_open()) {
  10.             throw std::runtime_error("无法打开文件: " + path);
  11.         }
  12.         validate_header(); // 可能抛出自定义异常
  13.     }
  14.     // 析构函数:自动关闭文件(无需手动操作)
  15.     ~SafeFile() noexcept = default;
  16.     // 成员函数:确保操作后仍满足不变式
  17.     void write(const std::string& data) {
  18.         std::string temp = encrypt(data); // 可能抛异常
  19.         file_ << temp;
  20.         if (file_.fail()) {
  21.             throw std::runtime_error("写入失败");
  22.         }
  23.     }
  24. private:
  25.     std::ofstream file_;
  26.     void validate_header() {
  27.         char header[4];
  28.         file_.read(header, sizeof(header));
  29.         if (!is_valid(header)) {
  30.             throw std::invalid_argument("无效文件头");
  31.         }
  32.     }
  33. };
复制代码

3. 复合对象:数据库事务

  1. #include <memory>
  2. #include <vector>
  3. class DatabaseTransaction {
  4. public:
  5.     // 构造函数:按顺序初始化RAII成员
  6.     DatabaseTransaction(const std::string& conn_str)
  7.         : logger_("transaction.log"),   // RAII成员1:日志文件
  8.           conn_(connect(conn_str)),     // RAII成员2:数据库连接
  9.           lock_(conn_.mutex())          // RAII成员3:互斥锁
  10.     {
  11.         if (!conn_.is_active()) {
  12.             throw std::runtime_error("数据库连接失败");
  13.         }
  14.         conn_.begin(); // 开启事务
  15.     }
  16.     // 析构函数:根据事务成功与否提交或回滚
  17.     ~DatabaseTransaction() noexcept {
  18.         try {
  19.             if (std::uncaught_exceptions() > 0 || !committed_) {
  20.                 conn_.rollback();
  21.             }
  22.         } catch (...) {} // 确保析构函数不抛出
  23.     }
  24.     void commit() {
  25.         validate_operations(); // 可能抛异常
  26.         conn_.commit();
  27.         committed_ = true;
  28.     }
  29.     void execute(const std::string& sql) {
  30.         conn_.execute(sql); // 可能抛异常
  31.         operations_.push_back(sql);
  32.     }
  33. private:
  34.     FileRAII logger_;           // 日志文件RAII管理
  35.     DatabaseConnection conn_;  // 数据库连接RAII对象
  36.     std::unique_lock<std::mutex> lock_; // 锁RAII管理
  37.     std::vector<std::string> operations_;
  38.     bool committed_ = false;
  39. };
复制代码

4. 强非常安全包管:Copy-and-Swap

  1. class ConfigManager {
  2. public:
  3.     // 修改配置(强异常安全保证)
  4.     void update(const std::string& key, const std::string& value) {
  5.         auto temp = data_;          // 1. 创建副本
  6.         temp[key] = value;          // 2. 修改副本(可能抛异常)
  7.         data_.swap(temp);           // 3. 无异常则原子交换
  8.     }
  9. private:
  10.     std::map<std::string, std::string> data_;
  11. };
复制代码

5. 维护不变式的关键点

5.1 构造函数中的非常处置处罚

  1. class TemperatureSensor {
  2. public:
  3.     explicit TemperatureSensor(int id)
  4.         : handle_(init_sensor(id)) // RAII成员初始化
  5.     {
  6.         if (get_current_temp() < ABSOLUTE_ZERO) { // 违反不变式
  7.             throw std::logic_error("传感器数据异常");
  8.         }
  9.     }
  10. private:
  11.     SensorHandleRAII handle_; // 传感器资源由RAII管理
  12. };
复制代码
5.2 成员函数的非常安全

  1. class Account {
  2. public:
  3.     void transfer(Account& to, double amount) {
  4.         if (amount <= 0 || balance_ < amount) {
  5.             throw std::invalid_argument("无效金额");
  6.         }
  7.         auto temp_from = balance_ - amount; // 不直接修改成员
  8.         auto temp_to = to.balance_ + amount;
  9.         
  10.         balance_ = temp_from;  // 无异常则提交修改
  11.         to.balance_ = temp_to;
  12.     }
  13. private:
  14.     double balance_ = 0.0;
  15. };
复制代码

6. 非常处置处罚与资源开释

6.1 多层调用中的资源传递

  1. void process_data() {
  2.     SafeFile input("input.dat"); // RAII对象1
  3.     SafeFile output("output.dat"); // RAII对象2
  4.     try {
  5.         auto data = parse(input); // 可能抛异常
  6.         transform(data);
  7.         output.write(data);
  8.     } catch (const ParseError& e) {
  9.         log_error("解析失败: ", e.what());
  10.         throw; // 重新抛出,input/output自动关闭
  11.     }
  12. }
复制代码

7. 设计原则总结

原则实现方法示例构造函数建立不变式若初始化失败,立即抛出非常throw std::runtime_error(...)析构函数开释资源所有资源由RAII成员管理,析构函数标记为noexcept~FileRAII() noexcept成员函数强非常安全利用Copy-and-Swap或事务模式temp.swap(data_)资源获取序次按声明序次初始化RAII成员logger_先于conn_初始化非常流传仅在能处置处罚的层级捕获非常UI层捕获并显示错误
错误处置处罚决议树

  1. 是否违反类不变式?
  2. ├── 是 → 抛出异常阻止对象创建
  3. └── 否 → 操作是否可能失败?
  4.     ├── 是 → 使用RAII + 异常传递
  5.     └── 否 → 直接执行操作
复制代码

通过结合RAII和非常处置处罚,可以确保:

  • 资源安全:无论是否发生非常,资源都会被正确开释。
  • 状态一致性:对象始终保持有效状态。
  • 代码简便性:消除冗余的错误查抄代码。
关键准则:每个类的设计都应明确其不变式,并通过RAII和非常处置处罚在构造函数、成员函数中强制维护这些不变式。
18 资源句柄优于弱结构化的finally。

在C++中,利用 资源句柄(RAII) 相比类似finally的弱结构化清理机制具有明显上风,尤其在资源管理、代码安全性和可维护性方面。以下是关键对比和详细示例:

1. 作用域控制的天然上风

资源句柄(RAII)示例

  1. void process_file() {
  2.     std::ifstream file("data.txt"); // 资源句柄:文件打开即初始化
  3.     parse(file);                   // 使用资源
  4. } // 此处自动调用~ifstream()关闭文件
复制代码
类finally结构示例(伪代码)

  1. void unsafe_process() {
  2.     FILE* fp = fopen("data.txt", "r");
  3.     try {
  4.         parse(fp);
  5.     } finally { // 虚构语法
  6.         fclose(fp); // 需要显式清理
  7.     }
  8. }
复制代码
核心差异


  • RAII资源生命周期与代码块作用域 严格绑定
  • finally必要 手动指定 清理代码位置,易遗漏或误用

2. 多资源管理复杂度对比

RAII主动处置处罚资源依赖

  1. void secure_operation() {
  2.     std::mutex mtx;
  3.     std::lock_guard<std::mutex> lock(mtx);  // 资源1:互斥锁
  4.     std::ofstream log("audit.log");         // 资源2:日志文件
  5.     db_operation();                        // 可能抛异常
  6. } // 自动先释放log,再释放lock(逆初始化顺序)
复制代码
finally结构的繁琐管理

  1. void error_prone_operation() {
  2.     Mutex mtx;
  3.     FileHandle log;
  4.     try {
  5.         mtx.lock();
  6.         log = open("audit.log");
  7.         db_operation();
  8.     } finally {
  9.         log.close(); // 需注意释放顺序
  10.         mtx.unlock(); // 与加锁顺序相反
  11.     }
  12. }
复制代码
问题暴露


  • finally块中需 手动维护资源开释序次(与获取序次相反)
  • 新增资源时需修改多处代码,易堕落

3. 非常安全性的根本差异

RAII在非常时的举动

  1. void raii_example() {
  2.     ResourceA a;          // 构造成功
  3.     ResourceB b;          // 构造失败,抛出异常
  4. } // a的析构函数自动调用,资源释放
复制代码
finally在非常时的陷阱

  1. void finally_example() {
  2.     ResourceA* a = new ResourceA();
  3.     try {
  4.         ResourceB* b = new ResourceB(); // 抛异常
  5.     } finally {
  6.         delete a; // 执行,但b未被释放(未进入try块)
  7.     }
  8. }
复制代码
关键缺陷


  • finally无法处置处罚 构造函数内抛出的非常(如ResourceB构造失败)
  • RAII在 任何控制流退出路径(包罗非常)都能触发析构

4. 代码可维护性对比

RAII的自我文档化

  1. class EncryptedConnection {
  2. public:
  3.     EncryptedConnection(const Endpoint& ep)
  4.         : socket_(ep.address),  // 先建立socket
  5.           cipher_(generate_key()) // 再初始化加密
  6.     {} // 明确资源初始化顺序
  7. private:
  8.     TcpSocket socket_;   // 资源1:网络连接
  9.     CipherContext cipher_; // 资源2:加密上下文
  10. };
复制代码
finally的隐式依赖

  1. void connect() {
  2.     Socket s = new Socket();
  3.     try {
  4.         Cipher c = new Cipher();
  5.         try {
  6.             s.connect(endpoint);
  7.             c.init(s.getKey());
  8.         } finally {
  9.             c.release(); // 需了解c依赖s
  10.         }
  11.     } finally {
  12.         s.close();
  13.     }
  14. }
复制代码
维护成本


  • finally要求开发者 显式影象资源依赖关系
  • 修改资源初始化序次需重构多个finally块

5. 性能与编译器优化

RAII的零开销抽象

  1. // 编译后代码(伪汇编):
  2. process_file:
  3.     call std::ifstream constructor
  4.     call parse
  5.     call std::ifstream destructor
  6.     ret
复制代码
finally的运行时成本

  1. // 伪代码:finally实现需要额外状态跟踪
  2. void function() {
  3.     register_cleanup(cleanup_code); // 运行时注册清理函数
  4.     // ...主逻辑...
  5.     execute_cleanup(); // 退出时执行
  6. }
复制代码
性能差异


  • RAII依赖编译时生成的析构函数调用,无运行时开销
  • finally通常必要 运行时栈记录清理操纵,影响性能

6. 复杂控制流中的可靠性

RAII处置处罚提前返回

  1. void early_return_example() {
  2.     AuditLog log("ops.log"); // 构造即管理
  3.     if (!check_permission()) return; // 自动清理log
  4.     critical_operation();
  5. } // log在此处析构
复制代码
finally需覆盖所有出口

  1. void finally_risky() {
  2.     File f = openFile();
  3.     try {
  4.         if (!checkPerm()) return; // 直接返回,跳过finally
  5.         // ...操作...
  6.     } finally {
  7.         f.close(); // 仅在try块退出时执行
  8.     }
  9.     // 此处f未关闭!
  10. }
复制代码
弊端分析


  • finally仅处置处罚 try块退出,无法捕获函数中其他返回路径
  • RAII覆盖 所有可能的控制流路径

总结:资源句柄的核心上风

特性RAII资源句柄finally结构作用域管理主动绑定生命周期需手动指定清理位置多资源序次依赖声明序次,主动逆序析构需手动维护开释序次非常安全性构造函数失败仍能清理已初始化的资源无法处置处罚try块外的构造函数非常代码简便性资源获取即管理,无需显式清理每个资源需配套try-finally块性能零运行时开销需额外状态跟踪维护成本低(新增资源不影响现有代码)高(需修改多个finally块) 结论:在C++中,RAII资源句柄通过

  • 作用域绑定
  • 主动析构序次
  • 非常安全包管
  • 零开销抽象
    成为资源管理的首选方案,远优于必要手动维护的finally模式。对于从其他语言转向C++的开发者,明白并应用RAII是编写工业级健壮代码的关键。
19 为你的不变式设计错误处置处罚战略。

在C++中,为类的不变式(Class Invariants)设计错误处置处罚战略必要结合 非常处置处罚RAII技术,确保对象始终处于有效状态。以下是分层的错误处置处罚方案和详细实现示例:

一、不变式验证的核心战略

1. 构造函数强制校验

原则:构造函数必须完成所有不变式的校验,失败时抛出非常,制止创建无效对象。
  1. class TemperatureSensor {
  2. public:
  3.     explicit TemperatureSensor(int id)
  4.         : handle_(init_sensor(id))  // RAII管理硬件资源
  5.     {
  6.         // 校验传感器初始读数是否符合不变式
  7.         float initial = read_temperature();
  8.         if (initial < -273.15f) {
  9.             throw std::logic_error("传感器读数违反物理定律");
  10.         }
  11.     }
  12. private:
  13.     SensorHandle handle_;  // RAII成员,自动释放资源
  14. };
复制代码
2. 成员函数的强非常安全

原则:修改对象状态的操纵必须包管 强非常安全(要么成功,要么不影响原状态)。
  1. class BankAccount {
  2. public:
  3.     void transfer(BankAccount& to, double amount) {
  4.         // 1. 校验不变式:金额必须非负且足够
  5.         if (amount <= 0 || balance_ < amount) {
  6.             throw std::invalid_argument("无效转账金额");
  7.         }
  8.         // 2. 操作副本,避免直接修改成员变量
  9.         double new_from = balance_ - amount;
  10.         double new_to = to.balance_ + amount;
  11.         // 3. 无异常则提交修改(原子操作)
  12.         balance_ = new_from;
  13.         to.balance_ = new_to;
  14.     }
  15. private:
  16.     double balance_ = 0.0;
  17. };
复制代码

二、错误处置处罚分层设计

1. 底层(资源层)



  • 目的:确保资源正确获取和开释。
  • 战略:利用RAII类封装资源,构造函数失败时抛出非常。
  1. class DatabaseConnection {
  2. public:
  3.     explicit DatabaseConnection(const std::string& conn_str)
  4.         : conn_handle_(connect(conn_str))  // 可能抛异常
  5.     {
  6.         if (!conn_handle_.active()) {
  7.             throw std::runtime_error("数据库连接失败");
  8.         }
  9.     }
  10.     // 析构函数自动断开连接(noexcept)
  11.     ~DatabaseConnection() noexcept {
  12.         if (conn_handle_.active()) disconnect(conn_handle_);
  13.     }
  14. private:
  15.     ConnHandle conn_handle_;  // RAII资源句柄
  16. };
复制代码
2. 中间层(业务逻辑)



  • 目的:转换技术非常为业务语义非常,添加上下文信息。
  • 战略:捕获底层非常,包装后重新抛出。
  1. class OrderProcessor {
  2. public:
  3.     void process_order(const Order& order) {
  4.         try {
  5.             DatabaseConnection db("user=admin;password=1234");
  6.             db.execute(order.to_sql());
  7.         } catch (const DatabaseException& e) {
  8.             // 添加业务上下文后重新抛出
  9.             throw OrderException("订单处理失败: " + order.id(), e);
  10.         }
  11.     }
  12. };
复制代码
3. 顶层(UI/API层)



  • 目的:终极处置处罚非常,展示友好信息或记录日记。
  • 战略:集中捕获所有未处置处罚非常,确保程序优雅降级。
  1. int main() {
  2.     try {
  3.         OrderProcessor processor;
  4.         processor.run();
  5.     } catch (const OrderException& e) {
  6.         std::cerr << "业务错误: " << e.what() << std::endl;
  7.         log_error(e);
  8.         return 1;
  9.     } catch (const std::exception& e) {
  10.         std::cerr << "系统错误: " << e.what() << std::endl;
  11.         log_critical(e);
  12.         return 2;
  13.     }
  14. }
复制代码

三、进阶错误处置处罚技术

1. 自定义非常类

用途:携带更多错误上下文(错误码、时间戳、业务ID等)。
  1. class NetworkException : public std::runtime_error {
  2. public:
  3.     NetworkException(const std::string& msg, int error_code, std::string url)
  4.         : std::runtime_error(msg),
  5.           error_code_(error_code),
  6.           url_(std::move(url)),
  7.           timestamp_(std::chrono::system_clock::now()) {}
  8.     int code() const noexcept { return error_code_; }
  9.     const std::string& url() const { return url_; }
  10.     std::time_t time() const {
  11.         return std::chrono::system_clock::to_time_t(timestamp_);
  12.     }
  13. private:
  14.     int error_code_;
  15.     std::string url_;
  16.     std::chrono::system_clock::time_point timestamp_;
  17. };
复制代码
2. 不变式规复机制

场景:在关键体系中尝试主动规复(如重新毗连硬件)。
  1. class RoboticArmController {
  2. public:
  3.     void move_to(Position target) {
  4.         try {
  5.             internal_move(target);
  6.         } catch (const HardwareException& e) {
  7.             if (attempt_recovery()) {  // 尝试恢复不变式
  8.                 internal_move(target); // 重试操作
  9.             } else {
  10.                 throw;  // 恢复失败,传递异常
  11.             }
  12.         }
  13.     }
  14. private:
  15.     bool attempt_recovery() {
  16.         reset_driver();  // 尝试重置硬件驱动
  17.         return calibrate();  // 返回是否恢复成功
  18.     }
  19. };
复制代码

四、错误处置处罚决议树

     
五、最佳实践总结

原则实现方式示例构造函数严格校验失败时抛出非常,制止无效对象生成throw std::invalid_argument成员函数强安全先操纵副本,再原子提交修改temp.swap(data_)非常信息丰富化自定义非常类携带错误上下文NetworkException资源主动开释RAII成员管理资源,析构函数标记为noexcept~DatabaseConnection() noexcept分层处置处罚技术非常在底层抛出,业务层转换语义catch (DBException&) 转 OrderException 通过遵循这些战略,可以构建出 高鲁棒性 的C++体系,确保不变式被粉碎时程序举动可猜测且安全。
20 能在编译时查抄的东西最幸亏编译时查抄(利用static_assert)。

在C++中,利用 static_assert 在编译时进行条件查抄,可以提前捕获潜在错误,提升代码健壮性并消除运行时开销。以下是关键应用场景和代码示例:

一、底子类型束缚

1. 验证类型大小

确保类型满意特定内存结构要求:
  1. // 必须为4字节类型(如int32_t)
  2. struct PacketHeader {
  3.     uint32_t type;
  4.     uint32_t length;
  5.     static_assert(sizeof(PacketHeader) == 8, "PacketHeader大小必须为8字节");
  6. };
复制代码
2. 查抄平台兼容性

确保类型在差别平台上的表现一致:
  1. // 验证指针大小为8字节(64位系统)
  2. static_assert(sizeof(void*) == 8, "仅支持64位架构");
复制代码

二、模板元编程束缚

1. 限定模板参数类型

确保模板参数为整数类型:
  1. template <typename T>
  2. class IntegerWrapper {
  3.     static_assert(std::is_integral_v<T>, "T必须是整数类型");
  4. public:
  5.     T value;
  6. };
  7. // 合法使用
  8. IntegerWrapper<int> iw_ok{42};
  9. // 编译错误:类型不匹配
  10. IntegerWrapper<float> iw_err{3.14f};
复制代码
2. 验证模板参数关系

确保模板参数之间有正确的继承关系:
  1. template <typename Base, typename Derived>
  2. void safe_cast(Derived& d) {
  3.     static_assert(std::is_base_of_v<Base, Derived>,
  4.         "Derived必须继承自Base");
  5.     // 安全转换逻辑...
  6. }
复制代码

三、常量表达式验证

1. 数组大小合法性

编译时验证数组维度:
  1. constexpr int MatrixSize = 16;
  2. class Matrix {
  3.     float data[MatrixSize][MatrixSize];
  4.     static_assert(MatrixSize > 0 && (MatrixSize & (MatrixSize - 1)) == 0,
  5.         "矩阵大小必须是2的幂");
  6. };
复制代码
2. 罗列值范围查抄

确保罗列值在有效范围内:
  1. enum class Color : uint8_t { Red = 1, Green = 2, Blue = 3 };
  2. template <Color C>
  3. struct ColorInfo {
  4.     static_assert(C >= Color::Red && C <= Color::Blue,
  5.         "无效的颜色值");
  6.     // 颜色处理逻辑...
  7. };
复制代码

四、自定义类型特性查抄

1. 验证特定接口存在

利用SFINAE或C++20概念束缚:
  1. // 检查类型是否有serialize方法
  2. template <typename T>
  3. struct has_serialize {
  4.     template <typename U>
  5.     static auto test(U*) -> decltype(std::declval<U>().serialize(), std::true_type{});
  6.     static auto test(...) -> std::false_type;
  7.     static constexpr bool value = decltype(test((T*)nullptr))::value;
  8. };
  9. template <typename T>
  10. void save(const T& obj) {
  11.     static_assert(has_serialize<T>::value, "T必须实现serialize方法");
  12.     obj.serialize();
  13. }
复制代码
2. 确保移动语义正确性

验证类型是否为可移动构造:
  1. template <typename T>
  2. class OptimizedContainer {
  3.     static_assert(std::is_move_constructible_v<T>,
  4.         "T必须支持移动构造");
  5.     // 使用移动语义优化存储...
  6. };
复制代码

五、配置参数校验

1. 编译时配置文件验证

确保配置参数合法:
  1. constexpr int MaxConnections = 100;
  2. constexpr int CurrentConnections = 150;
  3. // 检查连接数是否超限
  4. static_assert(CurrentConnections <= MaxConnections,
  5.     "当前连接数超过最大限制");
复制代码
2. 算法参数束缚

验证算法参数的数学有效性:
  1. template <int N>
  2. struct Factorial {
  3.     static_assert(N >= 0, "阶乘参数必须非负");
  4.     static constexpr int value = N * Factorial<N-1>::value;
  5. };
  6. template <>
  7. struct Factorial<0> { static constexpr int value = 1; };
复制代码

六、错误处置处罚战略对比

查抄类型编译时查抄 (static_assert)运行时查抄 (assert或非常)触发机遇编译阶段程序运行时性能影响无额外开销可能引入分支判断和非常处置处罚开销错误定位直接定位源码位置需调试或日记分析适用场景类型特性、常量表达式、模板参数等确定性问题用户输入、文件状态等动态不确定性问题
七、最佳实践总结


  • 优先编译时查抄:对类型、常量表达式等确定性问题利用static_assert
  • 结合类型特性库:利用<type_traits>中的工具简化束缚条件
  • 明确错误信息:提供清晰的静态断言消息,方便开发者定位问题
  • 避免滥用:动态条件(如用户输入)仍需运行时查抄
通过将尽可能多的查抄移至编译时,可以明显提升代码质量和运行效率,减少调试成本。
21 用你的错误处置处罚战略实验差别层级的查抄。

在C++中,通过分层错误处置处罚战略可以在差别层级实验针对性查抄,确保体系的健壮性和可维护性。以下为分层的错误处置处罚方案及代码示例:

一、分层错误处置处罚战略

层级查抄目的技术本领错误处置处罚方式编译时类型安全、静态束缚static_assert、概念束缚编译失败,制止生成可实验文件数据访问层资源有效性、技术非常(如数据库毗连)RAII + 自定义非常类抛出技术非常业务逻辑层业务规则有效性(如订单状态)防御性编程 + 业务非常捕获技术非常,抛出业务非常UI/API层输入合法性、展示友好错误参数校验 + 全局非常处置处罚器转换非常为HTTP状态码/弹窗
二、编译时查抄(静态束缚)

1. 验证模板参数合法性

  1. template <typename T>
  2. class Vector3D {
  3.     static_assert(std::is_arithmetic_v<T>,
  4.         "Vector3D元素类型必须是算术类型");
  5. public:
  6.     T x, y, z;
  7. };
  8. // 合法使用
  9. Vector3D<float> v1;
  10. // 编译错误:static_assert失败
  11. Vector3D<std::string> v2;
复制代码
2. 确保平台特性

  1. // 验证是否为小端序架构
  2. static_assert(std::endian::native == std::endian::little,
  3.     "本系统仅支持小端序架构");
复制代码

三、数据访问层(RAII + 技术非常)

1. 数据库毗连管理

  1. class DatabaseConnection {
  2. public:
  3.     explicit DatabaseConnection(const std::string& conn_str)
  4.         : handle_(connect(conn_str)) // RAII初始化
  5.     {
  6.         if (!handle_.active()) {
  7.             throw DatabaseException("连接失败", conn_str, errno);
  8.         }
  9.     }
  10.     void execute(const std::string& sql) {
  11.         if (auto code = handle_.query(sql); code != 0) {
  12.             throw QueryException("查询失败", sql, code);
  13.         }
  14.     }
  15. private:
  16.     DBHandleRAII handle_; // RAII管理连接生命周期
  17. };
复制代码
2. 文件操纵非常

  1. void parse_config(const std::string& path) {
  2.     SafeFile file(path); // RAII自动开/关文件
  3.     if (!file.validate_signature()) {
  4.         throw FileFormatException("无效文件签名", path);
  5.     }
  6.     // 解析操作...
  7. }
复制代码

四、业务逻辑层(业务非常转换)

1. 订单处置处罚

  1. class OrderProcessor {
  2. public:
  3.     void process(const Order& order) {
  4.         try {
  5.             check_inventory(order); // 可能抛DatabaseException
  6.             deduct_stock(order);
  7.             create_shipping(order);
  8.         } catch (const DatabaseException& e) {
  9.             // 添加业务上下文后重新抛出
  10.             throw OrderProcessingException("订单处理失败", order.id(), e);
  11.         }
  12.     }
  13. private:
  14.     void check_inventory(const Order& order) {
  15.         if (order.quantity() <= 0) {
  16.             throw InvalidOrderException("订单数量无效", order.id());
  17.         }
  18.     }
  19. };
复制代码
2. 付出网关调用

  1. class PaymentService {
  2. public:
  3.     Receipt charge(CreditCard card, double amount) {
  4.         if (amount <= 0) {
  5.             throw InvalidAmountException("金额必须为正数", amount);
  6.         }
  7.         try {
  8.             return gateway_.charge(card, amount); // 可能抛NetworkException
  9.         } catch (const NetworkException& e) {
  10.             throw PaymentFailedException("支付网关错误", e.details());
  11.         }
  12.     }
  13. };
复制代码

五、UI/API层(全局非常处置处罚)

1. REST API错误处置处罚

  1. // 全局异常处理器(基于Crow框架示例)
  2. CROW_ROUTE(app, "/api/order")([](const crow::request& req){
  3.     try {
  4.         Order order = parse_order(req.body);
  5.         OrderProcessor().process(order);
  6.         return crow::response(200);
  7.     } catch (const OrderProcessingException& e) {
  8.         // 业务异常:返回4xx状态码
  9.         return crow::response(400, json{{"error", e.what()}});
  10.     } catch (const std::exception& e) {
  11.         // 系统异常:记录日志,返回5xx
  12.         log_critical(e.what());
  13.         return crow::response(500);
  14.     }
  15. });
复制代码
2. GUI应用错误提示

  1. void MainWindow::onSubmitOrder() {
  2.     try {
  3.         Order order = ui_gather_input();
  4.         order_processor_.submit(order);
  5.         show_success("订单提交成功");
  6.     } catch (const InvalidInputException& e) {
  7.         show_error("输入错误", e.field_hint());
  8.     } catch (const PaymentFailedException& e) {
  9.         show_retry_dialog(e.retry_advice());
  10.     } catch (...) {
  11.         show_fatal_error("系统发生未知错误");
  12.     }
  13. }
复制代码

六、错误处置处罚工具链

工具/技术适用层级用途static_assert编译时强制类型/平台束缚自定义非常体系所有运行时层传递丰富错误上下文RAII包装类数据访问层主动资源清理全局非常捕获UI/API层防止瓦解,统一错误格式化日记体系所有层错误追踪和审计
七、分层战略上风


  • 关注点分离:每层仅处置处罚职责内的错误类型
  • 错误信息丰富化:非常在传递过程中携带更多上下文
  • 资源安全:RAII确保任何层级抛出非常都不会走漏资源
  • 用户体验优化:顶层将技术细节转换为友好提示
  • 维护性提升:编译时查抄减少运行时错误可能性
通过这种分层战略,可以构建出既健壮又易于维护的C++体系,各层级错误处置处罚职责明确,且能有效协作。
22 假如函数不会抛出非常,把它声明成noexcept的。

在C++中,假如一个函数确实不会抛出任何非常,将其声明为noexcept具有多重上风,但也需谨慎评估其适用性。以下是分步调的总结和发起:
1. 确定函数是否真正不会抛出非常



  • 查抄所有内部操纵:确认函数内部调用的所有函数、操纵符和构造函数均不会抛出非常。

    • 底子类型操纵(如算术运算)通常不会抛出非常。
    • 动态内存分配(new)、标准库容器操纵(如std::vector::push_back)可能抛出std::bad_alloc等非常。
    • 文件、网络等I/O操纵可能因外部因素失败并抛出非常。

  • 处置处罚潜在非常:若函数内部可能抛出非常,但已通过try-catch块完全捕获并处置处罚,确保无非常流传到函数外。
2. 声明函数为noexcept



  • 语法示例
    1. void safe_function() noexcept {
    2.     // 确保此处代码不会抛出异常
    3. }
    复制代码
  • 移动构造函数/赋值运算符
    1. class MyClass {
    2. public:
    3.     MyClass(MyClass&& other) noexcept {
    4.         // 移动资源,保证不抛出异常
    5.     }
    6.    
    7.     MyClass& operator=(MyClass&& other) noexcept {
    8.         // 移动赋值,保证不抛出异常
    9.         return *this;
    10.     }
    11. };
    复制代码

    • 标准库(如std::vector)会优先利用noexcept移动操纵提升性能。

3. 性能与优化



  • 编译器优化:noexcept答应编译器省略非常处置处罚机制(如栈展开表),生成更高效的代码。
  • 标准库优化

    • 容器操纵(如std::vector扩容)在元素类型支持noexcept移动时,优先利用移动而非复制。
    • 算法(如std::sort)可能因noexcept得到性能提升。

4. 接口设计与文档



  • 明确左券:noexcept是函数接口的一部分,告知调用者无需预备非常处置处罚。
  • 维护束缚:一旦声明noexcept,后续修改必须维持其不抛出非常的承诺,否则导致未定义举动。
5. 特别情况处置处罚



  • 虚函数:若基类虚函数声明为noexcept,所有派生类重写版本也必须保持noexcept,否则编译错误。
    1. class Base {
    2. public:
    3.     virtual void func() noexcept = 0;
    4. };
    5. class Derived : public Base {
    6. public:
    7.     void func() noexcept override { /* ... */ }
    8. };
    复制代码
  • 条件性noexcept:在模板中,根据类型特性动态决定是否noexcept。
    1. template<typename T>
    2. void swap(T& a, T& b) noexcept(noexcept(T(std::move(a))) && noexcept(a = std::move(b))) {
    3.     // 根据T的移动操作是否noexcept决定自身异常规范
    4. }
    复制代码
6. 风险与注意事项



  • 错误利用结果:若函数实际可能抛出非常却被声明为noexcept,非常触发时直接调用std::terminate()终止程序。
  • 维护成本:修改函数实现时,需重新验证noexcept的适用性,避免粉碎左券。
7. 推荐实践



  • 简朴函数:如纯算术运算、获取器(getters)等明显无非常的函数,应声明noexcept。
  • 移动操纵:移动构造函数和赋值运算符应尽量实现为noexcept。
  • 避免滥用:对于可能抛出非常或涉及外部资源的函数,谨慎评估后再决定。
  • 静态分析工具:利用Clang-Tidy等工具查抄noexcept的误用。
示例对比

未利用noexcept:
  1. void process_data() {
  2.     std::vector<int> data;
  3.     data.reserve(1000); // 可能抛出std::bad_alloc
  4.     // ...其他操作...
  5. }
复制代码
利用noexcept(错误示例,可能导致瓦解):
  1. void process_data() noexcept {
  2.     std::vector<int> data;
  3.     data.reserve(1000); // 若抛出异常,程序直接终止
  4. }
复制代码
正确做法(处置处罚非常或避免noexcept):
  1. void process_data() {
  2.     try {
  3.         std::vector<int> data;
  4.         data.reserve(1000);
  5.     } catch (const std::bad_alloc& e) {
  6.         // 处理内存不足,如降级方案
  7.     }
  8. }
复制代码
总结



  • 优先声明:对明确无非常的函数(如简朴盘算、移动操纵)利用noexcept,提升性能和代码质量。
  • 谨慎评估:涉及资源操纵的函数需确保非常被完全处置处罚,避免误用noexcept导致程序不稳固。
  • 团队规范:统一项目的noexcept利用标准,结合代码审查和静态分析确保正确性。
23 不要利用非常说明。

在C++中,动态非常规范(比方 void func() throw(int);)已在C++11中被标记为废弃,并在C++17中完全移除。以下是避免利用非常说明的详细缘故原由及现取代代方案:

一、为什么不利用非常说明?

1. 运行时查抄而非编译时



  • 问题:动态非常规范在运行时验证,若函数抛出未声明的非常类型,会触发 std::unexpected(),导致程序终止。
  • 示例
    1. void func() throw(int) {
    2.     throw "error"; // 抛出const char*,但未在声明中列出
    3. }
    复制代码

    • 编译通过,但运行时会瓦解。

2. 性能开销



  • 问题:编译器需生成额外代码来查抄非常类型,纵然未抛出任何非常。
  • 对比:noexcept无运行时开销,仅影响编译优化。
3. 维护成本高



  • 问题:修改函数可能抛出的非常类型时,需手动更新所有相关声明,易堕落。
  • 示例
    1. // 旧声明
    2. void process() throw(FileError);
    3. // 修改后需抛出NetworkError
    4. void process() throw(FileError, NetworkError); // 需手动更新
    复制代码
4. 无法与模板协同



  • 问题:模板函数无法为所有可能的类型指定动态非常规范。
  • 示例
    1. template<typename T>
    2. void swap(T& a, T& b) throw(); // 不现实,因T的拷贝可能抛出异常
    复制代码

二、替代方案:现代C++非常处置处罚战略

1. 利用 noexcept 明确不抛非常



  • 用途:声明函数不会抛出任何非常。
  • 上风

    • 编译时标记,无运行时开销。
    • 答应编译器优化(如移动语义优化)。

  • 示例
    1. void safe_operation() noexcept {
    2.     // 确保此处代码不会抛出异常
    3. }
    复制代码
2. 强非常安全包管



  • 原则:通过RAII和noexcept移动操纵实现强非常安全。
  • 示例
    1. class DataContainer {
    2. public:
    3.     DataContainer(DataContainer&& other) noexcept
    4.         : data_(std::move(other.data_)) {}
    5.    
    6.     // 强保证:要么完全成功,要么无副作用
    7.     void update() {
    8.         auto temp = data_;  // 先操作副本
    9.         temp.modify();
    10.         data_.swap(temp);   // 无异常则提交
    11.     }
    12. private:
    13.     std::vector<int> data_;
    14. };
    复制代码
3. 基于左券的编程



  • 工具:利用assert或static_assert在关键位置验证前置/后置条件。
  • 示例
    1. void process(int* ptr) {
    2.     assert(ptr != nullptr && "指针不能为空");
    3.     // 安全操作ptr
    4. }
    复制代码
4. 错误码 + 结构化返回



  • 场景:性能敏感或禁用非常的环境(如嵌入式体系)。
  • 示例
    1. enum class Error { Success, InvalidInput, Timeout };
    2. std::pair<Result, Error> safe_operation(Input input) {
    3.     if (!input.valid()) return { {}, Error::InvalidInput };
    4.     // 处理逻辑...
    5.     return { result, Error::Success };
    6. }
    复制代码
5. 自定义非常体系



  • 原则:通过继承std::exception定义清晰的非常类型,传递上下文信息。
  • 示例
    1. class NetworkException : public std::runtime_error {
    2. public:
    3.     NetworkException(const std::string& url, int code)
    4.         : std::runtime_error("Network error: " + url),
    5.           error_code_(code) {}
    6.     int code() const noexcept { return error_code_; }
    7. private:
    8.     int error_code_;
    9. };
    复制代码

三、迁徙旧代码中的非常说明

1. 更换 throw() 为 noexcept



  • 旧代码
    1. void legacy_func() throw(); // C++03风格
    复制代码
  • 新代码
    1. void legacy_func() noexcept; // C++11+风格
    复制代码
2. 删除详细非常类型声明



  • 旧代码
    1. void parse() throw(FileError, FormatError); // 已废弃
    复制代码
  • 新代码
    1. void parse(); // 不限制异常类型,但需在文档中说明可能抛出的异常
    复制代码
3. 利用静态分析工具



  • 工具:Clang-Tidy的 modernize-use-noexcept 查抄项可主动更换throw()为noexcept。

四、总结:最佳实践

场景处置处罚方式工具/技术函数绝不抛非常利用noexcept移动构造函数、简朴工具函数可能抛非常明确非常类型(继承std::exception)自定义非常类 + 文档说明资源管理RAII + 智能指针std::unique_ptr, 自定义RAII类输入校验断言 + 错误码assert, std:ptional高性能场景禁用非常 + 错误码编译器选项-fno-exceptions
通过避免过期的非常说明,接纳现代C++的非常处置处罚战略,可以明显提升代码的安全性性能可维护性
24 用引用的方式捕获层次体系中的非常。

在C++中,当处置处罚具有层次结构的非常体系时,通过引用捕获非常(catch (const BaseException& e))是最安全、最机动的方式。这种方式能够保持非常的多态性,避免对象切片(Object Slicing),同时答应高效访问非常信息。以下是详细说明和最佳实践:

1. 非常层次结构设计

定义基类非常

  1. #include <stdexcept>
  2. #include <string>
  3. // 基类异常,继承自标准异常
  4. class BaseException : public std::exception {
  5. public:
  6.     BaseException(const std::string& msg, int code = 0)
  7.         : msg_(msg), code_(code) {}
  8.     const char* what() const noexcept override {
  9.         return msg_.c_str();
  10.     }
  11.     int code() const noexcept { return code_; }
  12. private:
  13.     std::string msg_;
  14.     int code_;
  15. };
  16. // 派生异常类:文件操作异常
  17. class FileException : public BaseException {
  18. public:
  19.     FileException(const std::string& path, int errno_code)
  20.         : BaseException("文件错误: " + path, errno_code), path_(path) {}
  21.     const std::string& path() const { return path_; }
  22. private:
  23.     std::string path_;
  24. };
  25. // 派生异常类:网络异常
  26. class NetworkException : public BaseException {
  27. public:
  28.     NetworkException(const std::string& url, int http_status)
  29.         : BaseException("网络错误: " + url, http_status), url_(url) {}
  30.     const std::string& url() const { return url_; }
  31. private:
  32.     std::string url_;
  33. };
复制代码

2. 抛出非常

在必要的地方抛出详细的派生类非常:
  1. void load_file(const std::string& path) {
  2.     if (!file_exists(path)) {
  3.         throw FileException(path, ENOENT); // 抛出文件不存在异常
  4.     }
  5.     // ...其他操作...
  6. }
  7. void fetch_data(const std::string& url) {
  8.     if (http_get(url).status != 200) {
  9.         throw NetworkException(url, 500); // 抛出网络异常
  10.     }
  11. }
复制代码

3. 通过引用捕获非常

3.1 基本捕获方式

  1. int main() {
  2.     try {
  3.         load_file("data.txt");
  4.         fetch_data("https://example.com");
  5.     } catch (const FileException& e) {
  6.         // 捕获文件异常
  7.         std::cerr << "文件错误: " << e.what()
  8.                   << "\n路径: " << e.path()
  9.                   << "\n错误码: " << e.code() << std::endl;
  10.     } catch (const NetworkException& e) {
  11.         // 捕获网络异常
  12.         std::cerr << "网络错误: " << e.what()
  13.                   << "\nURL: " << e.url()
  14.                   << "\nHTTP状态码: " << e.code() << std::endl;
  15.     } catch (const BaseException& e) {
  16.         // 捕获基类异常(其他派生类)
  17.         std::cerr << "基础错误: " << e.what()
  18.                   << "\n错误码: " << e.code() << std::endl;
  19.     } catch (const std::exception& e) {
  20.         // 捕获标准异常
  21.         std::cerr << "标准异常: " << e.what() << std::endl;
  22.     } catch (...) {
  23.         // 捕获所有其他异常
  24.         std::cerr << "未知异常" << std::endl;
  25.     }
  26. }
复制代码
3.2 关键上风



  • 避免对象切片
    假如通过值捕获(catch (BaseException e)),派生类对象会被切割为基类对象,丢失派生类特有数据(如FileException::path_)。
  • 支持多态访问
    通过引用可以正确调用派生类的虚函数(如what())。
  • 高效性
    引用捕获避免了拷贝非常对象的开销。

4. 捕获序次与原则

4.1 从详细到一般

捕获序次应从最详细的非常到最通用的非常,确保每个非常类型都能被正确处置处罚:
  1. try {
  2.     // ...可能抛出FileException、NetworkException...
  3. } catch (const FileException& e) {       // 先捕获具体异常
  4.     handle_file_error(e);
  5. } catch (const NetworkException& e) {    // 再捕获其他具体异常
  6.     handle_network_error(e);
  7. } catch (const BaseException& e) {       // 最后捕获基类异常
  8.     handle_generic_error(e);
  9. }
复制代码
4.2 不要忽略基类捕获

纵然所有已知非常都已处置处罚,也应生存基类或std::exception的捕获块,避免未处置处罚的非常导致程序终止:
  1. try {
  2.     // ...
  3. } catch (const FileException& e) {
  4.     // 处理文件异常
  5. } catch (const BaseException& e) {
  6.     // 处理其他自定义异常
  7. } catch (const std::exception& e) {
  8.     // 处理标准库异常
  9. } catch (...) {
  10.     // 处理未知异常(如第三方库抛出的int、字符串等)
  11. }
复制代码

5. 动态类型查抄(dynamic_cast)

假如必要根据非常类型实验差别逻辑,可通过dynamic_cast安全转换:
  1. try {
  2.     // ...
  3. } catch (const BaseException& e) {
  4.     if (auto* file_ex = dynamic_cast<const FileException*>(&e)) {
  5.         // 处理文件异常
  6.         std::cout << "文件路径: " << file_ex->path() << std::endl;
  7.     } else if (auto* net_ex = dynamic_cast<const NetworkException*>(&e)) {
  8.         // 处理网络异常
  9.         std::cout << "请求URL: " << net_ex->url() << std::endl;
  10.     } else {
  11.         // 其他基类异常
  12.     }
  13. }
复制代码

6. 最佳实践总结

原则实现方式示例非常设计构建层次化的非常体系,继承自std::exceptionclass FileException : public BaseException抛出非常在得当位置抛出详细的派生类非常throw FileException(path, errno)引用捕获利用const&捕获非常catch (const FileException& e)捕获序次从详细到一般先FileException,后BaseException避免对象切片绝不通过值捕获多态非常不消catch (BaseException e)非常安全结合RAII管理资源std::lock_guard, 智能指针
7. 错误处置处罚决议树

     
通过引用捕获层次化的非常,结合清晰的非常类型设计,可以构建出既机动又安全的错误处置处罚体系。
25 并非每个非常都派生自exception类。

在C++中,确实存在不继承自std::exception的非常类型。这些非常可能是底子类型(如int、字符串字面量)、自定义类或第三方库定义的非常。为确保程序能正确处置处罚所有可能的非常,需接纳更机动的捕获战略。以下是分层次的解决方案和代码示例:

1. 底子类型非常处置处罚

示例:捕获int错误码

  1. try {
  2.     if (error_condition) {
  3.         throw 404; // 抛出整型错误码
  4.     }
  5. } catch (int code) {
  6.     std::cerr << "错误码: " << code << std::endl;
  7. }
复制代码
示例:捕获const char*字符串

  1. try {
  2.     throw "未知错误发生"; // 抛出C风格字符串
  3. } catch (const char* msg) {
  4.     std::cerr << "错误信息: " << msg << std::endl;
  5. }
复制代码

2. 第三方库非常处置处罚

示例:处置处罚第三方库抛出的非常

假设第三方库ThirdPartyLib可能抛出其自定义的LibException类:
  1. try {
  2.     ThirdPartyLib::operation(); // 可能抛出LibException
  3. } catch (const ThirdPartyLib::LibException& e) {
  4.     // 直接处理第三方异常
  5.     std::cerr << "第三方库错误: " << e.what() << std::endl;
  6. } catch (...) {
  7.     // 兜底处理其他未知异常
  8.     std::cerr << "未知第三方错误" << std::endl;
  9. }
复制代码

3. 统一非常接口设计

3.1 封装非标准非常

将第三方或底子类型非常封装为继承自std::exception的自定义非常:
  1. class UnifiedException : public std::exception {
  2. public:
  3.     UnifiedException(const std::string& msg) : msg_(msg) {}
  4.     const char* what() const noexcept override { return msg_.c_str(); }
  5. private:
  6.     std::string msg_;
  7. };
  8. void safe_third_party_call() {
  9.     try {
  10.         ThirdPartyLib::operation();
  11.     } catch (const ThirdPartyLib::LibException& e) {
  12.         throw UnifiedException("第三方错误: " + std::string(e.what()));
  13.     } catch (int code) {
  14.         throw UnifiedException("错误码: " + std::to_string(code));
  15.     } catch (...) {
  16.         throw UnifiedException("未知第三方异常");
  17.     }
  18. }
  19. // 使用示例
  20. try {
  21.     safe_third_party_call();
  22. } catch (const std::exception& e) {
  23.     // 统一处理为std::exception
  24.     std::cerr << e.what() << std::endl;
  25. }
复制代码
3.2 利用std::exception_ptr(C++11+)

跨层传递恣意类型的非常:
  1. std::exception_ptr eptr;
  2. void risky_operation() {
  3.     try {
  4.         ThirdPartyLib::operation(); // 可能抛出任何类型
  5.     } catch (...) {
  6.         eptr = std::current_exception(); // 捕获异常指针
  7.     }
  8. }
  9. void handle_exception() {
  10.     if (eptr) {
  11.         try {
  12.             std::rethrow_exception(eptr);
  13.         } catch (const std::exception& e) {
  14.             std::cerr << "标准异常: " << e.what() << std::endl;
  15.         } catch (int code) {
  16.             std::cerr << "错误码: " << code << std::endl;
  17.         } catch (...) {
  18.             std::cerr << "未知异常类型" << std::endl;
  19.         }
  20.     }
  21. }
复制代码

4. 全面捕获战略

4.1 从详细到一般的catch序次

  1. try {
  2.     // 可能抛出多种异常
  3. } catch (const MyCustomException& e) {
  4.     // 处理最具体的自定义异常
  5. } catch (const ThirdPartyLib::LibException& e) {
  6.     // 处理第三方异常
  7. } catch (const std::exception& e) {
  8.     // 处理标准异常
  9. } catch (const char* msg) {
  10.     // 处理字符串异常
  11. } catch (int code) {
  12.     // 处理整型错误码
  13. } catch (...) {
  14.     // 兜底处理其他所有异常
  15. }
复制代码
4.2 记录未知非常

  1. try {
  2.     // ...
  3. } catch (...) {
  4.     std::cerr << "发生未知异常,程序将终止" << std::endl;
  5.     std::terminate(); // 或执行其他恢复逻辑
  6. }
复制代码

5. 非常安全与资源管理

结合RAII确保资源安全开释:
  1. class FileRAII {
  2. public:
  3.     FileRAII(const std::string& path) : file_(fopen(path.c_str(), "r")) {
  4.         if (!file_) throw UnifiedException("无法打开文件");
  5.     }
  6.     ~FileRAII() { if (file_) fclose(file_); }
  7. private:
  8.     FILE* file_;
  9. };
  10. void process_file() {
  11.     FileRAII file("data.txt"); // 异常安全
  12.     // 使用文件...
  13.     // 即使抛出异常,文件也会正确关闭
  14. }
复制代码

总结:处置处罚非标准非常的关键点

场景战略工具/技术底子类型非常直接catch特定类型catch(int), catch(const char*)第三方库非常封装或直接处置处罚自定义包装函数统一非常接口继承std::exception或封装UnifiedException类未知非常处置处罚利用catch(...)兜底结合日记记录和终止逻辑资源安全RAII管理资源智能指针、自定义RAII类 通过机动组合这些战略,可以确保程序正确处置处罚所有类型的非常,同时保持代码的健壮性和可维护性。
26 让main()捕获和报告所有非常。

在C++中,可以通过在main()函数中利用try-catch块来捕获所有非常,并结合分层处置处罚战略确保程序优雅退出。以下是实现方案及代码示例:

1. 底子框架:捕获所有非常类型

  1. #include <iostream>
  2. #include <exception>
  3. #include <cstdlib> // EXIT_FAILURE
  4. int main() {
  5.     try {
  6.         // 主程序逻辑
  7.         return 0;
  8.     }
  9.     // 1. 优先捕获标准异常体系
  10.     catch (const std::exception& e) {
  11.         std::cerr << "标准异常: " << e.what() << std::endl;
  12.     }
  13.     // 2. 捕获字符串异常
  14.     catch (const char* msg) {
  15.         std::cerr << "C风格异常: " << msg << std::endl;
  16.     }
  17.     // 3. 捕获整型错误码
  18.     catch (int code) {
  19.         std::cerr << "错误码: " << code << std::endl;
  20.     }
  21.     // 4. 兜底捕获其他所有异常
  22.     catch (...) {
  23.         std::cerr << "未知类型异常" << std::endl;
  24.     }
  25.    
  26.     // 异常退出码
  27.     return EXIT_FAILURE;
  28. }
复制代码

2. 分层捕获战略

2.1 优先处置处罚详细非常

  1. try {
  2.     // 主逻辑
  3. }
  4. catch (const NetworkTimeoutException& e) {  // 自定义网络超时异常
  5.     std::cerr << "[网络] 操作超时: " << e.url() << std::endl;
  6. }
  7. catch (const FileIOException& e) {          // 自定义文件异常
  8.     std::cerr << "[文件] 错误路径: " << e.path() << std::endl;
  9. }
  10. catch (const std::invalid_argument& e) {   // 标准库参数异常
  11.     std::cerr << "[参数] " << e.what() << std::endl;
  12. }
  13. catch (const std::exception& e) {           // 其他标准异常
  14.     std::cerr << "[标准] " << e.what() << std::endl;
  15. }
  16. catch (...) {                               // 兜底
  17.     std::cerr << "无法识别的异常" << std::endl;
  18. }
复制代码
2.2 记录非常堆栈(必要平台支持)

  1. #include <execinfo.h> // Linux回溯
  2. void print_stacktrace() {
  3.     void* buffer[64];
  4.     int size = backtrace(buffer, 64);
  5.     char** symbols = backtrace_symbols(buffer, size);
  6.     for (int i = 0; i < size; ++i) {
  7.         std::cerr << symbols[i] << std::endl;
  8.     }
  9.     free(symbols);
  10. }
  11. catch (...) {
  12.     std::cerr << "异常发生,堆栈追踪:" << std::endl;
  13.     print_stacktrace();
  14.     return EXIT_FAILURE;
  15. }
复制代码

3. 自定义非常处置处罚扩展

3.1 统一非常接口

  1. class BaseException : public std::exception {
  2. public:
  3.     BaseException(const std::string& msg) : msg_(msg) {}
  4.     const char* what() const noexcept override { return msg_.c_str(); }
  5. private:
  6.     std::string msg_;
  7. };
  8. class NetworkException : public BaseException {
  9. public:
  10.     NetworkException(const std::string& url, int code)
  11.         : BaseException("网络错误: " + url + " (代码: " + std::to_string(code) + ")") {}
  12. };
复制代码
3.2 非常上下文增强

  1. catch (const BaseException& e) {
  2.     std::cerr << "[自定义] " << e.what() << std::endl;
  3.     // 可在此记录额外信息(如时间戳、会话ID)
  4. }
复制代码

4. 全局非常处置处罚(可选)

4.1 设置全局非常处置处罚器

  1. #include <csignal>
  2. #include <csetjmp>
  3. std::jmp_buf env;
  4. void signal_handler(int sig) {
  5.     std::cerr << "致命信号: " << sig << std::endl;
  6.     std::_Exit(EXIT_FAILURE);
  7. }
  8. void terminate_handler() {
  9.     std::cerr << "未捕获异常导致程序终止" << std::endl;
  10.     std::_Exit(EXIT_FAILURE);
  11. }
  12. int main() {
  13.     std::signal(SIGSEGV, signal_handler);
  14.     std::set_terminate(terminate_handler);
  15.     // ... try-catch 块 ...
  16. }
复制代码

5. 示例:完整工作流

  1. #include <iostream>
  2. #include <stdexcept>
  3. #include <cstdlib>
  4. void risky_operation(bool fail) {
  5.     if (fail) {
  6.         throw std::runtime_error("模拟操作失败");
  7.     }
  8.     std::cout << "操作成功" << std::endl;
  9. }
  10. int main() {
  11.     try {
  12.         risky_operation(true); // 触发异常
  13.         return 0;
  14.     } catch (const std::runtime_error& e) {
  15.         std::cerr << "运行时错误: " << e.what() << std::endl;
  16.     } catch (const std::exception& e) {
  17.         std::cerr << "标准异常: " << e.what() << std::endl;
  18.     } catch (...) {
  19.         std::cerr << "未知异常" << std::endl;
  20.     }
  21.     return EXIT_FAILURE;
  22. }
复制代码
输出
  1. 运行时错误: 模拟操作失败
复制代码

6. 关键原则

原则实现方式从详细到一般优先捕获详细非常类型,最后catch(...)兜底资源开释包管利用RAII管理资源,确保非常后主动清理错误信息丰富化自定义非常类携带上下文(如错误码、时间戳)跨平台兼容性避免依赖平台特定的非常处置处罚机制(如SEH)日记集成将非常信息写入日记体系,便于事后分析 通过这种分层设计,main()函数能够捕获并报告所有层级的非常,同时确保程序状态可控,资源安全开释。
27 销毁信息前先要找到它的替代者。

在C++中,“销毁信息前先找到替代者” 的战略对于包管数据完整性和体系稳固性至关重要。以下是分步调的详细实现方案及代码示例:

1. 内存管理:先分配新内存,再开释旧内存

动态数组扩容示例

  1. #include <algorithm>
  2. #include <stdexcept>
  3. class DynamicArray {
  4. public:
  5.     void resize(size_t new_size) {
  6.         // 步骤1:分配新内存
  7.         int* new_data = new (std::nothrow) int[new_size];
  8.         if (!new_data) throw std::bad_alloc();
  9.         // 步骤2:复制旧数据到新内存
  10.         size_t copy_size = std::min(size_, new_size);
  11.         std::copy(data_, data_ + copy_size, new_data);
  12.         // 步骤3:安全销毁旧数据(仅在步骤1、2成功后执行)
  13.         delete[] data_;
  14.         data_ = new_data;
  15.         size_ = new_size;
  16.     }
  17. private:
  18.     int* data_ = nullptr;
  19.     size_t size_ = 0;
  20. };
复制代码

2. 文件操纵:先创建临时文件,再更换原文件

原子性文件更新

  1. #include <fstream>
  2. #include <cstdio>
  3. void safe_file_write(const std::string& path, const std::string& content) {
  4.     // 步骤1:写入临时文件
  5.     std::string temp_path = path + ".tmp";
  6.     {
  7.         std::ofstream tmp(temp_path);
  8.         if (!tmp) throw std::runtime_error("无法创建临时文件");
  9.         tmp << content;
  10.     } // 文件流关闭确保数据刷入磁盘
  11.     // 步骤2:重命名临时文件替换原文件(原子操作)
  12.     if (std::rename(temp_path.c_str(), path.c_str()) != 0) {
  13.         std::remove(temp_path.c_str()); // 清理临时文件
  14.         throw std::runtime_error("文件替换失败");
  15.     }
  16. }
复制代码

3. 数据结构:先构建新节点,再更新指针

链表节点安全更换

  1. class LinkedList {
  2.     struct Node {
  3.         int data;
  4.         Node* next;
  5.     };
  6. public:
  7.     void update_node(int old_value, int new_value) {
  8.         // 步骤1:创建新节点(可能抛异常)
  9.         Node* new_node = new Node{new_value, nullptr};
  10.         // 步骤2:定位旧节点并链接新节点
  11.         Node* current = head_;
  12.         Node* prev = nullptr;
  13.         while (current && current->data != old_value) {
  14.             prev = current;
  15.             current = current->next;
  16.         }
  17.         if (!current) {
  18.             delete new_node; // 未找到旧节点,清理新节点
  19.             throw std::invalid_argument("值不存在");
  20.         }
  21.         // 步骤3:连接新节点到链表
  22.         new_node->next = current->next;
  23.         if (prev) {
  24.             prev->next = new_node;
  25.         } else {
  26.             head_ = new_node;
  27.         }
  28.         // 步骤4:安全删除旧节点
  29.         delete current;
  30.     }
  31. private:
  32.     Node* head_ = nullptr;
  33. };
复制代码

4. 多线程安全:先预备数据,再原子更换

无锁共享指针更换

  1. #include <atomic>
  2. #include <memory>
  3. class ThreadSafeData {
  4. public:
  5.     void update_data(const std::string& new_data) {
  6.         // 步骤1:创建新数据副本
  7.         auto new_ptr = std::make_shared<std::string>(new_data);
  8.         // 步骤2:原子替换旧指针
  9.         std::atomic_store_explicit(&data_ptr_, new_ptr, std::memory_order_release);
  10.     }
  11.     std::string get_data() const {
  12.         // 原子获取当前数据指针
  13.         auto ptr = std::atomic_load_explicit(&data_ptr_, std::memory_order_acquire);
  14.         return ptr ? *ptr : "";
  15.     }
  16. private:
  17.     std::shared_ptr<std::string> data_ptr_;
  18. };
复制代码

5. 数据库事务:先验证新数据,再提交修改

SQLite事务示例

  1. #include <sqlite3.h>
  2. void safe_db_update(sqlite3* db, int id, const std::string& new_value) {
  3.     sqlite3_stmt* stmt = nullptr;
  4.    
  5.     try {
  6.         // 步骤1:开始事务
  7.         if (sqlite3_exec(db, "BEGIN TRANSACTION", 0, 0, 0) != SQLITE_OK) {
  8.             throw std::runtime_error("事务启动失败");
  9.         }
  10.         // 步骤2:准备更新语句
  11.         const char* sql = "UPDATE table SET value=? WHERE id=?";
  12.         if (sqlite3_prepare_v2(db, sql, -1, &stmt, 0) != SQLITE_OK) {
  13.             throw std::runtime_error("SQL准备失败");
  14.         }
  15.         // 步骤3:绑定新值并执行
  16.         sqlite3_bind_text(stmt, 1, new_value.c_str(), -1, SQLITE_STATIC);
  17.         sqlite3_bind_int(stmt, 2, id);
  18.         if (sqlite3_step(stmt) != SQLITE_DONE) {
  19.             throw std::runtime_error("更新失败");
  20.         }
  21.         // 步骤4:提交事务
  22.         sqlite3_finalize(stmt);
  23.         if (sqlite3_exec(db, "COMMIT", 0, 0, 0) != SQLITE_OK) {
  24.             throw std::runtime_error("提交失败");
  25.         }
  26.     } catch (...) {
  27.         // 回滚事务并清理资源
  28.         sqlite3_exec(db, "ROLLBACK", 0, 0, 0);
  29.         sqlite3_finalize(stmt);
  30.         throw;
  31.     }
  32. }
复制代码

6. 设计原则总结

原则实现方法关键上风资源获取序次先构造新资源,再销毁旧资源避免资源真空期非常安全利用RAII和try-catch块确保非常发生时资源不走漏原子操纵利用std::atomic或体系级原子操纵包管多线程环境下的可见性和序次性事务处置处罚BEGIN/COMMIT/ROLLBACK模式数据库操纵的一致性数据备份写入临时文件后重定名防止写过程瓦解导致数据损坏
错误处置处罚决议树

     
通过遵循这些战略,可以确保在销毁旧信息前,其替代者已正确构建并验证,从而提升体系的鲁棒性和数据完整性。
28 在赋值运算中抛出非常前要确保运算对象处于有效状态。

在C++中,实现赋值运算符时,确保在抛出非常前对象处于有效状态是非常安全性的核心要求。以下是分步调的实现战略和代码示例:

1. 非常安全品级与赋值操纵

安全品级形貌赋值操纵实现要点基本包管操纵失败后对象仍处于有效状态不粉碎当前对象的成员数据强包管操纵要么完全成功,要么不影响原对象利用"拷贝并互换"(copy-and-swap)无抛出包管操纵承诺不抛出非常利用noexcept标记,仅限简朴操纵
2. 实现强非常安全的赋值操纵

2.1 拷贝并互换(Copy-and-Swap)惯用法

  1. class String {
  2. public:
  3.     // 拷贝构造函数(可能抛出bad_alloc)
  4.     String(const String& other)
  5.         : data_(new char[other.size_ + 1]), size_(other.size_) {
  6.         std::copy(other.data_, other.data_ + size_ + 1, data_);
  7.     }
  8.     // 交换操作(不抛异常)
  9.     void swap(String& other) noexcept {
  10.         std::swap(data_, other.data_);
  11.         std::swap(size_, other.size_);
  12.     }
  13.     // 赋值运算符(强异常安全)
  14.     String& operator=(const String& rhs) {
  15.         if (this != &rhs) {
  16.             String temp(rhs); // 1. 拷贝构造可能抛异常
  17.             swap(temp);        // 2. 交换无异常
  18.         }                     // 3. temp析构释放旧资源
  19.         return *this;
  20.     }
  21. private:
  22.     char* data_ = nullptr;
  23.     size_t size_ = 0;
  24. };
复制代码
关键点


  • 拷贝构造在前:所有可能抛出非常的操纵在修改当前对象前完成。
  • 互换无非常:swap()利用noexcept确保原子性资源转移。
  • 自赋值安全:通过if (this != &rhs)避免冗余操纵。

3. 处置处罚基本非常安全

当无法实现强包管时,至少确保对象有效:
  1. class SafeArray {
  2. public:
  3.     SafeArray& operator=(const SafeArray& rhs) {
  4.         if (this != &rhs) {
  5.             // 1. 分配新内存(可能抛bad_alloc)
  6.             int* new_data = new int[rhs.size_];
  7.             std::copy(rhs.data_, rhs.data_ + rhs.size_, new_data);
  8.             
  9.             // 2. 安全替换(无异常)
  10.             delete[] data_;
  11.             data_ = new_data;
  12.             size_ = rhs.size_;
  13.         }
  14.         return *this;
  15.     }
  16. private:
  17.     int* data_ = nullptr;
  18.     size_t size_ = 0;
  19. };
复制代码
风险


  • 若new int[...]抛出bad_alloc,原data_和size_保持不变(基本包管)。
  • 若std::copy抛出(如元素类型的拷贝抛非常),对象可能处于部分更新状态。

4. 验证非常安全

4.1 单元测试(利用Catch2框架)

  1. TEST_CASE("String赋值运算符强异常安全") {
  2.     String s1("Hello");
  3.     String s2("World");
  4.    
  5.     // 模拟拷贝构造函数抛出异常
  6.     auto throw_on_copy = [](const String&) -> String {
  7.         throw std::bad_alloc();
  8.     };
  9.    
  10.     REQUIRE_THROWS_AS(s1 = throw_on_copy(s2), std::bad_alloc);
  11.     REQUIRE(s1.str() == "Hello"); // 赋值失败后s1仍为原值
  12. }
复制代码
4.2 内存走漏检测(Valgrind)

  1. valgrind --leak-check=full ./your_program
复制代码

5. 总结:实现步调与原则

步调实现方式非常安全包管1. 资源拷贝创建临时对象或分配新资源强包管:失败不影响原对象2. 互换/提交利用noexcept的swap()或原子更换无非常3. 清理旧资源在临时对象析构中主动开释旧资源基本包管 核心原则


  • 先完成可能失败的操纵:在修改当前对象状态前完成所有可能抛出非常的操纵。
  • 资源管理主动化:依赖RAII(如智能指针)避免手动delete。
  • 自赋值查抄:避免冗余操纵和潜在错误。
29 不要让析构函数抛出非常。

在C++中,析构函数绝对不应该抛出非常。这是C++非常安全编程的黄金法则之一,由于析构函数在对象生命周期结束时会被主动调用,若此时抛出非常,会导致程序处于不可猜测的状态甚至直接瓦解。以下是详细缘故原由和解决方案:

一、为什么析构函数不能抛出非常?

1. 栈展开(Stack Unwinding)时的致命问题

当非常被抛出时,C++运行时体系会展开调用栈,逐个调用局部对象的析构函数。假如某个析构函数在栈展开过程中又抛出新的非常:


  • C++标准规定此时直接调用 std::terminate(),程序立即终止
  • 资源走漏:未完成的析构函数可能无法开释其他资源。
2. 非常处置处罚机制的冲突



  • 双重非常:若析构函数抛出非常时,当前已有非常在流传(比如在 catch 块中处置处罚其他非常),则触发 std::terminate()。
  • 违反非常安全包管:无法确保对象完整销毁。
3. 设计原则的粉碎



  • RAII失效:析构函数是资源开释的最后防线,必须包管可靠。

二、正确处置处罚析构函数中的非常

1. 在析构函数中捕获所有非常

  1. class FileHandler {
  2. public:
  3.     ~FileHandler() noexcept {
  4.         try {
  5.             if (file_.is_open()) {
  6.                 file_.close(); // 可能抛出异常
  7.             }
  8.         } catch (const std::exception& e) {
  9.             // 记录日志,但不重新抛出
  10.             std::cerr << "文件关闭失败: " << e.what() << std::endl;
  11.         }
  12.     }
  13. private:
  14.     std::fstream file_;
  15. };
复制代码
关键点


  • 利用 try-catch 块包裹可能抛出非常的代码。
  • 不重新抛出:在 catch 块中处置处罚错误(如记录日记),但不抛出新非常。
2. 将可能失败的操纵移出析构函数

  1. class DatabaseConnection {
  2. public:
  3.     // 显式关闭方法(用户可处理异常)
  4.     void close() {
  5.         if (conn_.active()) {
  6.             conn_.close(); // 可能抛出异常
  7.             conn_ = nullptr;
  8.         }
  9.     }
  10.     ~DatabaseConnection() noexcept {
  11.         try {
  12.             close(); // 析构时尝试关闭,但已处理异常
  13.         } catch (...) {
  14.             std::cerr << "数据库连接未正常关闭" << std::endl;
  15.         }
  16.     }
  17. private:
  18.     DBConnection conn_;
  19. };
复制代码
上风


  • 用户可显式调用 close() 并处置处罚非常。
  • 析构函数作为后备,确保资源终极被开释。

三、利用RAII避免非常

1. 智能指针主动管理资源

  1. class ResourceOwner {
  2. public:
  3.     ResourceOwner() : res_(std::make_unique<Resource>()) {}
  4.     // 无需自定义析构函数,unique_ptr自动释放资源
  5. private:
  6.     std::unique_ptr<Resource> res_;
  7. };
复制代码
2. 确保资源开释操纵无非常



  • 设计不可失败的接口
    1. class MutexGuard {
    2. public:
    3.     ~MutexGuard() noexcept {
    4.         mutex_.unlock(); // 假设unlock()永远不会失败
    5.     }
    6. private:
    7.     std::mutex& mutex_;
    8. };
    复制代码

四、代码验证与工具

1. 静态查抄工具



  • Clang-Tidy查抄
    1. clang-tidy -checks='-*,bugprone-exception-escape' your_file.cpp
    复制代码

    • 检测可能从析构函数抛出的非常。

2. 单元测试

  1. TEST_CASE("析构函数不抛异常") {
  2.     REQUIRE_NOTHROW([] {
  3.         FileHandler fh;
  4.     }());
  5. }
复制代码

五、总结:析构函数非常处置处罚原则

原则实现方式示例克制抛出非常析构函数标记为noexcept~ClassName() noexcept { ... }内部非常完全捕获用try-catch包裹可能失败的操纵文件关闭、网络毗连开释资源开释操纵无非常设计资源管理类,确保开释操纵可靠智能指针、RAII包装类提供显式开释方法答应用户处置处罚非常,析构函数作为后备close(), disconnect()
六、错误处置处罚决议树

     
通过遵循这些原则,可确保析构函数不会抛出非常,从而维护程序的稳固性和可猜测性。
30 把普通代码和非常处置处罚代码分离开来。

在C++中,将普通代码(业务逻辑)与非常处置处罚代码分离是提升代码可维护性和可读性的重要本领。以下是分步调的实现战略和代码示例:

一、核心设计原则

原则实现方式上风资源与逻辑分离利用RAII管理资源,避免非常处置处罚代码侵入业务逻辑业务代码专注流程,非常处置处罚主动完成分层非常处置处罚在独立层(如控制器、中间件)统一处置处罚非常避免重复try-catch块非常安全封装将可能抛出非常的代码封装到特定模块业务代码仅调用接口,不处置处罚细节错误传递战略利用非常或错误码规范错误流传路径统一错误信息格式,方便追踪
二、详细实现战略

1. RAII资源管理(主动清理,减少try-catch)

  1. // 业务代码:无需显式异常处理
  2. void process_data(const std::string& path) {
  3.     FileRAII file(path);  // RAII自动管理文件句柄
  4.     DataProcessor processor(file);
  5.     processor.analyze();
  6.     // 无需手动关闭文件,析构时自动处理
  7. }
  8. // RAII包装类
  9. class FileRAII {
  10. public:
  11.     explicit FileRAII(const std::string& path)
  12.         : file_(fopen(path.c_str(), "r")) {
  13.         if (!file_) throw FileOpenError(path);
  14.     }
  15.     ~FileRAII() noexcept { if (file_) fclose(file_); }
  16.     FILE* handle() const noexcept { return file_; }
  17. private:
  18.     FILE* file_;
  19. };
复制代码

2. 业务逻辑与非常处置处罚分层

  1. // 业务层:纯逻辑,不处理异常
  2. void business_operation() {
  3.     DatabaseConnection db("user:pass@host");
  4.     db.execute("UPDATE accounts SET balance = balance * 1.05");
  5. }
  6. // 控制层:统一异常处理
  7. int main() {
  8.     try {
  9.         business_operation();
  10.         return 0;
  11.     } catch (const DatabaseException& e) {
  12.         log_error("数据库错误:", e.what());
  13.         return 1;
  14.     } catch (const std::exception& e) {
  15.         log_error("系统错误:", e.what());
  16.         return 2;
  17.     } catch (...) {
  18.         log_error("未知错误");
  19.         return 3;
  20.     }
  21. }
复制代码

3. 非常生成与处置处罚模块化

  1. // 异常生成模块:封装可能失败的操作
  2. namespace risky_ops {
  3.     Image load_image(const std::string& path) {
  4.         if (!file_exists(path))
  5.             throw ImageLoadError("文件不存在: " + path);
  6.         return decode_image(path); // 可能抛异常
  7.     }
  8. }
  9. // 业务代码:调用模块化接口
  10. void display_image(const std::string& path) {
  11.     try {
  12.         auto img = risky_ops::load_image(path);
  13.         render(img);
  14.     } catch (...) {
  15.         // 仅在此处理UI相关错误(如显示错误弹窗)
  16.         show_error_dialog("图片加载失败");
  17.         throw; // 其他异常继续向上传递
  18.     }
  19. }
复制代码

4. 错误码与非常转换(混淆战略)

  1. // 底层:返回错误码
  2. ErrorCode low_level_operation(int param) {
  3.     if (param < 0) return ErrorCode::InvalidInput;
  4.     // ...操作...
  5.     return ErrorCode::Success;
  6. }
  7. // 中间层:将错误码转换为异常
  8. void mid_layer(int param) {
  9.     auto code = low_level_operation(param);
  10.     if (code != ErrorCode::Success) {
  11.         throw AppException("操作失败", static_cast<int>(code));
  12.     }
  13. }
  14. // 业务层:仅处理异常
  15. void business_logic() {
  16.     try {
  17.         mid_layer(42);
  18.     } catch (const AppException& e) {
  19.         // 处理业务异常
  20.     }
  21. }
复制代码

三、高级本领

1. 战略模式实现可插拔非常处置处罚

  1. class ErrorHandler {
  2. public:
  3.     virtual ~ErrorHandler() = default;
  4.     virtual void handle(const std::exception& e) const = 0;
  5. };
  6. class ConsoleHandler : public ErrorHandler {
  7. public:
  8.     void handle(const std::exception& e) const override {
  9.         std::cerr << "错误: " << e.what() << std::endl;
  10.     }
  11. };
  12. class DatabaseWriter {
  13.     std::unique_ptr<ErrorHandler> handler_;
  14. public:
  15.     explicit DatabaseWriter(std::unique_ptr<ErrorHandler> handler)
  16.         : handler_(std::move(handler)) {}
  17.    
  18.     void save(const Data& data) {
  19.         try {
  20.             db_.insert(data);
  21.         } catch (const std::exception& e) {
  22.             handler_->handle(e); // 委托给策略处理
  23.         }
  24.     }
  25. };
复制代码

2. 利用std:ptional或std::expected(C++23)减少非常

  1. // 业务代码使用optional处理可能失败的操作
  2. std::optional<Image> safe_load(const std::string& path) {
  3.     if (!validate_path(path)) return std::nullopt;
  4.     return decode_image(path); // 内部可能抛异常,但被封装
  5. }
  6. void display_image() {
  7.     if (auto img = safe_load("photo.jpg")) {
  8.         render(*img);
  9.     } else {
  10.         show_error("无效图片路径");
  11.     }
  12. }
复制代码

四、验证与调试

1. 单元测试分离

  1. // 测试业务逻辑(假设无异常)
  2. TEST_CASE("数据分析逻辑正确性") {
  3.     DataSet data = generate_test_data();
  4.     REQUIRE(process(data) == expected_result);
  5. }
  6. // 单独测试异常处理
  7. TEST_CASE("文件不存在时抛出异常") {
  8.     REQUIRE_THROWS_AS(load_image("invalid.jpg"), ImageLoadError);
  9. }
复制代码
2. 静态分析工具

  1. # 使用Clang-Tidy检查异常安全
  2. clang-tidy -checks='*' your_file.cpp -- -std=c++20
复制代码

五、总结:代码结构示例

  1. src/
  2. ├── core/            # 核心业务逻辑(无异常处理)
  3. │   ├── data_processor.cpp
  4. │   └── database.cpp
  5. ├── exceptions/      # 异常处理模块
  6. │   ├── handlers/    # 异常处理策略
  7. │   └── errors.cpp   # 自定义异常类
  8. └── main.cpp         # 统一异常捕获入口
复制代码
通过以上战略,可实现:

  • 业务代码纯净:专注于核心逻辑,无混杂的非常处置处罚代码
  • 非常处置处罚集中:统一管理错误日记、用户提示、资源回滚
  • 可维护性提升:修改非常战略时无需改动业务逻辑
  • 测试友好:业务逻辑和非常处置处罚可分别进行单元测试
31 当非常发生时,假如由new分配的内存尚未被开释将造成内存走漏,请注意这一点。

在C++中,当利用 new 分配内存后,若未正确开释且发生非常,会导致内存走漏。为确保非常安全,需遵循 RAII(Resource Acquisition Is Initialization) 原则,结合智能指针和公道的代码设计。以下是详细解决方案和代码示例:

一、问题根源与风险

错误示例:直接利用 new 导致走漏

  1. void risky_function() {
  2.     int* ptr = new int[100];  // 分配内存
  3.     some_operation();         // 可能抛异常
  4.     delete[] ptr;             // 若异常发生,此行不会执行!
  5. }
复制代码
风险:若 some_operation() 抛出非常,delete[] 无法实验,内存走漏。

二、解决方案

1. 利用智能指针(推荐)

智能指针(如 std::unique_ptr 和 std::shared_ptr)会在析构时主动开释内存,纵然发生非常。
示例:std::unique_ptr

  1. #include <memory>
  2. void safe_function() {
  3.     auto ptr = std::make_unique<int[]>(100);  // 自动管理内存
  4.     some_operation();  // 若抛异常,ptr 析构时自动释放内存
  5. }
复制代码
示例:std::shared_ptr

  1. void shared_resource() {
  2.     auto ptr = std::shared_ptr<int>(new int(42), [](int* p) { delete p; });
  3.     some_operation();  // 异常安全
  4. }
复制代码
2. 手动 try-catch 开释(不推荐)

若必须手动管理,需在 try 块中开释内存。
  1. void manual_management() {
  2.     int* ptr = nullptr;
  3.     try {
  4.         ptr = new int[100];
  5.         some_operation();
  6.         delete[] ptr;
  7.     } catch (...) {
  8.         delete[] ptr;  // 捕获异常后释放
  9.         throw;         // 重新抛出异常
  10.     }
  11. }
复制代码
缺点:代码冗余,易遗漏开释逻辑。

三、复杂场景:构造函数中的非常

问题:构造函数中分配多个资源

  1. class ResourceHolder {
  2. public:
  3.     ResourceHolder() {
  4.         ptr1 = new int[100];  // 分配资源1
  5.         ptr2 = new int[200];  // 分配资源2(可能抛异常)
  6.     }
  7.     ~ResourceHolder() { delete[] ptr1; delete[] ptr2; }
  8. private:
  9.     int* ptr1;
  10.     int* ptr2;
  11. };
复制代码
风险:若 ptr2 分配失败,ptr1 未被开释。
解决方案:用智能指针管理成员

  1. class SafeResourceHolder {
  2. public:
  3.     SafeResourceHolder()
  4.         : ptr1(std::make_unique<int[]>(100)),
  5.           ptr2(std::make_unique<int[]>(200)) {}
  6.     // 无需手动编写析构函数
  7. private:
  8.     std::unique_ptr<int[]> ptr1;
  9.     std::unique_ptr<int[]> ptr2;
  10. };
复制代码
上风:纵然构造函数中途失败,已分配的资源也会被主动开释。

四、进阶:自定义RAII类

封装文件句柄管理

  1. #include <cstdio>
  2. class FileRAII {
  3. public:
  4.     explicit FileRAII(const char* path) : file_(fopen(path, "r")) {
  5.         if (!file_) throw std::runtime_error("文件打开失败");
  6.     }
  7.     ~FileRAII() noexcept { if (file_) fclose(file_); }
  8.     FILE* handle() const noexcept { return file_; }
  9. private:
  10.     FILE* file_;
  11. };
  12. void process_file() {
  13.     FileRAII file("data.txt");  // 异常安全
  14.     // 使用 file.handle()
  15. }
复制代码

五、非常安全品级

品级形貌实现方式基本包管非常发生后程序状态有效,但可能部分修改确保所有资源被开释强包管非常发生后程序状态与调用前一致利用"拷贝并互换"(copy-and-swap)无抛出包管操纵绝不抛非常利用 noexcept 标记
六、错误处置处罚决议树

     
总结

战略适用场景上风智能指针常规动态内存管理主动开释,代码简便RAII封装类文件句柄、网络毗连等非内存资源统一资源生命周期管理手动try-catch遗留代码或特别需求机动但易堕落,需严格测试 通过将资源管理与对象生命周期绑定,可从根本上避免因非常导致的内存走漏。优先利用智能指针和RAII机制,而非手动管理。
32 函数假如能抛出一个非常,那么它就会抛出这个非常,遵循这一假设。

在C++中,遵循“若函数可能抛出非常,则必须确保非常正确抛出”的假设,必要通过以下战略实现健壮的非常安全性:

一、确保非常正确抛出的关键原则


  • 非常安全包管品级

    • 基本包管:非常发生时,对象仍处于有效状态,资源不走漏。
    • 强包管:操纵要么完全成功,要么不改变程序状态(原子性)。
    • 无抛出包管(noexcept):操纵绝不抛出非常。

  • 资源管理

    • 利用RAII(如智能指针、自定义资源句柄)确保资源主动开释。
    • 析构函数标记为noexcept,且绝不抛出非常。


二、实现非常正确抛出的代码规范

1. 显式抛出非常的条件查抄

  1. class DataProcessor {
  2. public:
  3.     void process(const std::string& input) {
  4.         if (input.empty()) {
  5.             throw std::invalid_argument("输入不可为空");
  6.         }
  7.         // 业务逻辑...
  8.     }
  9. };
复制代码
2. 利用RAII包管资源安全

  1. void safe_file_operation(const std::string& path) {
  2.     std::ofstream file(path); // RAII自动管理文件流
  3.     if (!file) {
  4.         throw std::runtime_error("无法打开文件: " + path);
  5.     }
  6.     // 文件操作...
  7. } // 文件流析构时自动关闭
复制代码
3. 强非常包管:Copy-and-Swap

  1. class Config {
  2. public:
  3.     void update(const std::string& key, const std::string& value) {
  4.         auto temp = data_;          // 拷贝原数据
  5.         temp[key] = value;          // 修改副本(可能抛异常)
  6.         data_.swap(temp);           // 无异常则原子交换
  7.     }
  8. private:
  9.     std::map<std::string, std::string> data_;
  10. };
复制代码
4. 非常流传与封装

  1. void high_level_operation() {
  2.     try {
  3.         low_level_operation(); // 可能抛异常
  4.     } catch (const LowLevelException& e) {
  5.         // 添加上下文后重新抛出
  6.         throw HighLevelException("高层操作失败", e);
  7.     }
  8. }
复制代码

三、非常处置处罚的代码分层

1. 业务层(纯逻辑,无try-catch)

  1. void business_logic() {
  2.     DatabaseConnection db("user:pass@host");
  3.     db.execute("UPDATE accounts SET balance = balance * 1.05");
  4. }
复制代码
2. 控制层(统一非常处置处罚)

  1. int main() {
  2.     try {
  3.         business_logic();
  4.         return 0;
  5.     } catch (const DatabaseException& e) {
  6.         std::cerr << "数据库错误: " << e.what() << std::endl;
  7.         return 1;
  8.     } catch (const std::exception& e) {
  9.         std::cerr << "系统错误: " << e.what() << std::endl;
  10.         return 2;
  11.     } catch (...) {
  12.         std::cerr << "未知异常" << std::endl;
  13.         return 3;
  14.     }
  15. }
复制代码

四、自定义非常类设计

1. 继承自std::exception

  1. class NetworkException : public std::runtime_error {
  2. public:
  3.     NetworkException(const std::string& url, int code)
  4.         : std::runtime_error("网络错误: " + url + " (代码: " + std::to_string(code) + ")"),
  5.           url_(url), code_(code) {}
  6.    
  7.     const std::string& url() const noexcept { return url_; }
  8.     int code() const noexcept { return code_; }
  9. private:
  10.     std::string url_;
  11.     int code_;
  12. };
复制代码
2. 利用非常链传递上下文

  1. try {
  2.     connect_to_server("https://example.com");
  3. } catch (const SocketException& e) {
  4.     throw NetworkException("example.com", 500).with_context(e);
  5. }
复制代码

五、工具与验证

1. 静态分析工具

  1. # 使用Clang-Tidy检查异常安全性
  2. clang-tidy -checks='*' your_file.cpp -- -std=c++20
复制代码
2. 单元测试验证

  1. TEST_CASE("空输入触发异常") {
  2.     DataProcessor processor;
  3.     REQUIRE_THROWS_AS(processor.process(""), std::invalid_argument);
  4. }
  5. TEST_CASE("文件打开失败时抛出异常") {
  6.     REQUIRE_THROWS_AS(safe_file_operation("/invalid/path"), std::runtime_error);
  7. }
复制代码

六、性能与非常处置处罚的平衡

场景战略工具/技术性能敏感路径禁用非常,利用错误码或std::expected-fno-exceptions编译选项可规复错误抛出自定义非常类非常层次结构设计不可规复错误终止程序(std::terminate)断言或日记记录后终止
七、总结:非常处置处罚决议树

     通过严格遵循这些原则和模式,可确保非常在预期场景下正确抛出,同时保持代码的健壮性和可维护性。
33 库不应自行终止程序,正确的做法是抛出一个非常然后由调用者决定该怎么做。

在C++库设计中,遵循“库不应自行终止程序,而应抛出非常”的原则,可确保调用者拥有完全的错误处置处罚控制权。以下是详细实现步调与示例:

一、设计原则


  • 绝不调用终止函数:避免利用 std::terminate、abort 或 exit。
  • 资源安全:通过RAII管理资源,确保非常抛出时无走漏。
  • 非常类型明确:自定义非常类,传递详细错误信息。
  • 文档清晰:明确标注可能抛出的非常类型及触发条件。

二、实现步调

1. 定义自定义非常类

  1. #include <stdexcept>
  2. #include <string>
  3. class LibraryException : public std::runtime_error {
  4. public:
  5.     explicit LibraryException(const std::string& msg, int error_code = 0)
  6.         : std::runtime_error(msg), error_code_(error_code) {}
  7.     int code() const noexcept { return error_code_; }
  8. private:
  9.     int error_code_;
  10. };
  11. class FileOpenException : public LibraryException {
  12. public:
  13.     explicit FileOpenException(const std::string& path, int errno_code)
  14.         : LibraryException("无法打开文件: " + path, errno_code), path_(path) {}
  15.     const std::string& path() const { return path_; }
  16. private:
  17.     std::string path_;
  18. };
复制代码
2. 资源管理:利用RAII

  1. class SafeFile {
  2. public:
  3.     explicit SafeFile(const std::string& path) : file_(fopen(path.c_str(), "r")) {
  4.         if (!file_) throw FileOpenException(path, errno);
  5.     }
  6.     ~SafeFile() noexcept { if (file_) fclose(file_); }
  7.     FILE* handle() const noexcept { return file_; }
  8. private:
  9.     FILE* file_;
  10. };
复制代码
3. 函数实现:抛出非常而非终止

  1. // 正确做法:抛出异常
  2. void process_data(const std::string& path) {
  3.     SafeFile file(path); // 可能抛出FileOpenException
  4.     // 处理文件...
  5. }
  6. // 错误做法:终止程序
  7. void bad_process_data(const std::string& path) {
  8.     FILE* file = fopen(path.c_str(), "r");
  9.     if (!file) {
  10.         std::cerr << "致命错误:无法打开文件" << std::endl;
  11.         std::exit(EXIT_FAILURE); // ❌ 库不应自行终止
  12.     }
  13.     // 处理文件...
  14.     fclose(file);
  15. }
复制代码
4. 错误流传:不吞噬非常

  1. void low_level_operation() {
  2.     if (critical_error_detected()) {
  3.         throw LibraryException("底层操作失败", error_code);
  4.     }
  5. }
  6. void high_level_api() {
  7.     try {
  8.         low_level_operation();
  9.     } catch (const LibraryException& e) {
  10.         // 可添加上下文后重新抛出
  11.         throw LibraryException("高层操作失败: " + std::string(e.what()), e.code());
  12.     }
  13. }
复制代码
5. 提供错误码选项(可选)

  1. enum class ErrorCode { Success = 0, InvalidInput, ResourceBusy };
  2. ErrorCode safe_operation(int param) noexcept {
  3.     try {
  4.         if (param < 0) throw LibraryException("参数无效", static_cast<int>(ErrorCode::InvalidInput));
  5.         // 操作...
  6.         return ErrorCode::Success;
  7.     } catch (const LibraryException& e) {
  8.         return static_cast<ErrorCode>(e.code());
  9.     } catch (...) {
  10.         return ErrorCode::ResourceBusy;
  11.     }
  12. }
复制代码

三、调用者处置处罚示例

  1. int main() {
  2.     try {
  3.         process_data("data.txt");
  4.     } catch (const FileOpenException& e) {
  5.         std::cerr << "文件错误: " << e.what()
  6.                   << "\n路径: " << e.path()
  7.                   << "\n系统错误码: " << e.code() << std::endl;
  8.         // 恢复策略:使用默认数据
  9.         load_default_data();
  10.     } catch (const LibraryException& e) {
  11.         std::cerr << "库错误[" << e.code() << "]: " << e.what() << std::endl;
  12.         return EXIT_FAILURE;
  13.     }
  14.     return EXIT_SUCCESS;
  15. }
复制代码

四、文档标注

在头文件中明确标注可能抛出的非常:
  1. /**
  2. * @brief 处理指定文件的数据
  3. * @param path 文件路径
  4. * @throws FileOpenException 文件无法打开时抛出
  5. * @throws LibraryException 其他库内部错误时抛出
  6. */
  7. void process_data(const std::string& path);
复制代码

五、测试验证

编写单元测试验证非常举动:
  1. #include <catch2/catch.hpp>
  2. TEST_CASE("文件打开失败时抛出FileOpenException") {
  3.     REQUIRE_THROWS_AS(process_data("nonexistent.txt"), FileOpenException);
  4. }
  5. TEST_CASE("无效参数触发LibraryException") {
  6.     REQUIRE_THROWS_AS(safe_operation(-1), LibraryException);
  7. }
复制代码

六、总结

原则实现方式上风非常而非终止用throw更换exit/abort调用者可机动处置处罚错误资源主动开释RAII类管理文件句柄、内存、锁等非常安全无走漏非常类型分层自定义非常继承自标准非常错误信息丰富且类型安全文档明确性头文件中标注@throws用户清晰了解可能的错误条件 通过此设计,库将错误控制权完全交给调用者,提升代码的健壮性和可维护性。
34 库不应该直接输出面向终极用户的错误诊断信息,正确的做法是抛出一个非常然后由调用者决定该怎么做。

在C++库设计中,避免直接输出用户可见的错误信息,转而通过非常机制将错误传递给调用者处置处罚,是提高机动性和可维护性的关键。以下是分步调的实现方案:

一、定义非常类体系

1. 底子非常类(继承自 std::exception)

  1. #include <stdexcept>
  2. #include <string>
  3. class LibraryException : public std::runtime_error {
  4. public:
  5.     explicit LibraryException(const std::string& msg, int error_code = 0)
  6.         : std::runtime_error(msg), error_code_(error_code) {}
  7.    
  8.     int code() const noexcept { return error_code_; }
  9.     virtual std::string details() const { return ""; }
  10. private:
  11.     int error_code_;
  12. };
复制代码
2. 详细非常类(按错误类型细化)

  1. // 文件操作异常
  2. class FileIOException : public LibraryException {
  3. public:
  4.     FileIOException(const std::string& path, int errno_code)
  5.         : LibraryException("文件I/O错误: " + path, errno_code), path_(path) {}
  6.    
  7.     std::string details() const override {
  8.         return "路径: " + path_ + ",系统错误码: " + std::to_string(code());
  9.     }
  10. private:
  11.     std::string path_;
  12. };
  13. // 网络异常
  14. class NetworkException : public LibraryException {
  15. public:
  16.     NetworkException(const std::string& url, int http_status)
  17.         : LibraryException("网络请求失败: " + url, http_status), url_(url) {}
  18.    
  19.     std::string details() const override {
  20.         return "URL: " + url_ + ",HTTP状态码: " + std::to_string(code());
  21.     }
  22. private:
  23.     std::string url_;
  24. };
复制代码

二、实现非常安全的库函数

1. 抛出非常而非输堕落误

  1. #include <fstream>
  2. #include <vector>
  3. std::vector<char> read_file(const std::string& path) {
  4.     std::ifstream file(path, std::ios::binary);
  5.     if (!file) {
  6.         throw FileIOException(path, errno); // 抛出而非输出到stderr
  7.     }
  8.    
  9.     file.seekg(0, std::ios::end);
  10.     size_t size = file.tellg();
  11.     file.seekg(0, std::ios::beg);
  12.    
  13.     std::vector<char> buffer(size);
  14.     if (!file.read(buffer.data(), size)) {
  15.         throw FileIOException(path, errno);
  16.     }
  17.    
  18.     return buffer;
  19. }
复制代码
2. 利用RAII管理资源

  1. class DatabaseConnection {
  2. public:
  3.     explicit DatabaseConnection(const std::string& conn_str)
  4.         : handle_(connect(conn_str))
  5.     {
  6.         if (!handle_.active()) {
  7.             throw NetworkException(conn_str, -1);
  8.         }
  9.     }
  10.    
  11.     void execute(const std::string& sql) {
  12.         // 执行SQL,失败时抛异常
  13.     }
  14. private:
  15.     DBHandle handle_; // RAII管理连接
  16. };
复制代码

三、调用者处置处罚非常

1. 捕获并处置处罚非常

  1. int main() {
  2.     try {
  3.         auto data = read_file("config.json");
  4.         DatabaseConnection db("user:pass@localhost");
  5.         db.execute("UPDATE settings SET value=1");
  6.     } catch (const FileIOException& e) {
  7.         // 记录到日志系统,而非直接输出
  8.         log_error("文件错误[代码%d]: %s\n详情: %s",
  9.             e.code(), e.what(), e.details().c_str());
  10.         return EXIT_FAILURE;
  11.     } catch (const NetworkException& e) {
  12.         show_user_alert("网络连接失败: " + e.details()); // 用户界面提示
  13.         return EXIT_FAILURE;
  14.     } catch (const LibraryException& e) {
  15.         log_error("库内部错误: %s (代码%d)", e.what(), e.code());
  16.         return EXIT_FAILURE;
  17.     } catch (...) {
  18.         log_error("未知异常");
  19.         return EXIT_FAILURE;
  20.     }
  21.     return EXIT_SUCCESS;
  22. }
复制代码

四、文档与接口规范

1. 头文件注释

  1. /**
  2. * @brief 读取文件内容到字节数组
  3. * @param path 文件路径
  4. * @return 包含文件内容的std::vector<char>
  5. * @throws FileIOException 文件打开或读取失败时抛出
  6. * @throws std::bad_alloc 内存不足时抛出
  7. */
  8. std::vector<char> read_file(const std::string& path);
复制代码
2. 非常类型文档

非常类触发场景携带信息FileIOException文件无法打开或读取文件路径、体系错误码NetworkException网络请求失败URL、HTTP状态码LibraryException库内部未分类错误错误消息、自定义错误码
五、单元测试验证

  1. #include <catch2/catch.hpp>
  2. TEST_CASE("读取不存在的文件应抛出FileIOException") {
  3.     REQUIRE_THROWS_AS(read_file("nonexistent.txt"), FileIOException);
  4. }
  5. TEST_CASE("网络连接失败时抛出NetworkException") {
  6.     REQUIRE_THROWS_AS(DatabaseConnection("invalid_conn"), NetworkException);
  7. }
复制代码

六、设计原则总结

原则实现方式上风非常而非输出抛出携带详细信息的非常类调用者机动处置处罚错误资源主动开释RAII类管理文件句柄、网络毗连等非常安全无走漏非常分类清晰继承体系区分差别错误类型精准捕获和处置处罚特定错误文档完整性头文件和独立文档形貌非常举动调用者明确了解错误条件 通过此设计,库将错误处置处罚权完全交给调用者,同时确保错误信息的丰富性和可追溯性,符合现代C++库的最佳实践。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

南七星之家

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表