自定义异常类通过继承std::runtime_error等标准异常,可提升C++程序的错误处理能力;示例包括直接继承传递消息、重写what()提供详细信息,以及添加成员变量记录上下文,如文件名和行号;关键在于正确实现what()方法并确保异常安全。

在C++中,自定义异常类可以让程序更清晰地处理错误情况,提升代码的可读性和健壮性。标准库中的std::exception及其派生类(如std::runtime_error、std::invalid_argument)已经提供了基础支持,但针对特定业务逻辑,我们通常需要定义自己的异常类型。
继承std::exception或其子类
最常见的方式是让自定义异常类继承自std::exception或其已有子类。推荐继承std::runtime_error等标准异常,因为它们已正确实现了what()方法,并支持传入字符串信息。
示例:
#include #includeclass MyException : public std::runtime_error {public:explicit MyException(const std::string& message): std::runtime_error(message) {}};
这样就能使用what()输出错误信息:
try { throw MyException("发生了一个自定义错误");} catch (const std::exception& e) { std::cout << e.what() << std::endl;}
重写what()方法(可选)
如果需要更复杂的错误描述,可以重写what()方法。注意返回的是const char*,所以建议内部使用std::string缓存信息。
立即学习“C++免费学习笔记(深入)”;
示例:
class DetailedException : public std::exception {private: std::string msg;public: explicit DetailedException(const std::string& info, int code) : msg("错误码: " + std::to_string(code) + ", 信息: " + info) {}const char* what() const noexcept override { return msg.c_str();}
};
抛出并捕获时:
throw DetailedException("文件打开失败", 404);
添加自定义成员函数和数据
自定义异常类还可以包含额外字段和方法,用于传递更丰富的错误上下文。
class FileException : public std::runtime_error {private: std::string filename; int line;public:FileException(const std::string& file, int l, const std::string& msg): std::runtime_error(msg), filename(file), line(l) {}
const std::string& getFilename() const { return filename; }int getLine() const { return line; }
};
使用时可以获取详细信息:
catch (const FileException& e) { std::cout << "文件: " << e.getFilename() << " 在第 " << e.getLine() << " 行出错: " << e.what() << std::endl;}
基本上就这些。继承标准异常类,合理使用构造函数传递信息,必要时扩展功能,就能写出清晰可靠的自定义异常。关键是确保what()安全返回字符串,且析构函数不抛异常。
以上就是c++++中如何自定义异常类_c++自定义异常类方法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1477472.html
微信扫一扫
支付宝扫一扫