在C++编程中,异常处理是保障程序健壮性的重要机制。标准库提供了一些基本的异常类型(如 std::exception),但在实际开发中,我们常常需要根据业务逻辑定义自己的异常类型。这就是C++自定义异常类的作用。
本文将手把手教你如何创建和使用C++自定义异常类,即使你是编程小白,也能轻松掌握!
标准异常类(如 std::runtime_error、std::logic_error)虽然通用,但缺乏对特定场景的语义表达。例如:
这些场景使用通用异常会降低代码可读性和维护性。而通过自定义异常,你可以让错误信息更清晰、调试更高效。
在C++中,自定义异常类通常继承自 std::exception 或其派生类(如 std::runtime_error)。最简单的方式是继承 std::exception 并重写 what() 方法。
#include <iostream>#include <exception>#include <string>class InsufficientFundsException : public std::exception {private: std::string message;public: explicit InsufficientFundsException(const std::string& msg) : message(msg) {} const char* what() const noexcept override { return message.c_str(); }};int main() { try { throw InsufficientFundsException("账户余额不足,无法完成转账!"); } catch (const InsufficientFundsException& e) { std::cerr << "捕获异常: " << e.what() << std::endl; } return 0;} 其实,std::runtime_error 已经帮我们实现了 what() 和消息存储,因此更简洁:
#include <iostream>#include <stdexcept> // 注意:这里要包含 <stdexcept>class NetworkTimeoutException : public std::runtime_error {public: explicit NetworkTimeoutException(const std::string& msg) : std::runtime_error(msg) {}};int main() { try { throw NetworkTimeoutException("连接服务器超时,请检查网络!"); } catch (const NetworkTimeoutException& e) { std::cerr << "网络错误: " << e.what() << std::endl; } return 0;} Exception 结尾,如 FileOpenException;std::runtime_error(运行时错误)或 std::logic_error(逻辑错误);explicit 防止隐式转换;what() 不抛出异常(用 noexcept 修饰)。#include <iostream>#include <stdexcept>class BalanceTooLowException : public std::runtime_error {public: BalanceTooLowException(double balance, double amount) : std::runtime_error( "余额不足!当前余额: " + std::to_string(balance) + ", 尝试转账: " + std::to_string(amount) ) {}};class InvalidAccountException : public std::runtime_error {public: explicit InvalidAccountException(const std::string& accountId) : std::runtime_error("无效账户ID: " + accountId) {}};void transfer(double balance, double amount, const std::string& toAccount) { if (amount > balance) { throw BalanceTooLowException(balance, amount); } if (toAccount.empty()) { throw InvalidAccountException(toAccount); } std::cout << "转账成功!" << std::endl;}int main() { try { transfer(100.0, 150.0, "ACC123"); } catch (const BalanceTooLowException& e) { std::cerr << "[余额异常] " << e.what() << std::endl; } catch (const InvalidAccountException& e) { std::cerr << "[账户异常] " << e.what() << std::endl; } return 0;} 这段代码展示了如何在真实场景中使用多个C++自定义异常类,使错误处理更加精准。
通过本文,你已经学会了:
std::exception 或 std::runtime_error 派生自己的异常;掌握C++异常处理技巧,是成为专业C++开发者的关键一步。赶快动手试试吧!
关键词回顾:C++自定义异常类、C++异常处理、自定义异常、C++编程教程
本文由主机测评网于2025-12-13发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025127350.html