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

在C++中,自定义异常类可以让程序更清晰地处理错误情况,提升代码的可读性和健壮性。标准库中的std::exception及其派生类(如std::runtime_error、std::invalid_argument)已经提供了基础支持,但针对特定业务逻辑,我们通常需要定义自己的异常类型。
最常见的方式是让自定义异常类继承自std::exception或其已有子类。推荐继承std::runtime_error等标准异常,因为它们已正确实现了what()方法,并支持传入字符串信息。
#include <stdexcept>
#include <string>
<p>class 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()方法。注意返回的是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) {}
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">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;
<p>public:
FileException(const std::string& file, int l, const std::string& msg)
: std::runtime_error(msg), filename(file), line(l) {}</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">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++自定义异常类方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号