自定义异常类需继承std::runtime_error等标准异常,可添加错误信息与成员函数,通过throw抛出并用try-catch按派生到基类顺序捕获处理。

在C++中,自定义异常类可以让你更精确地处理程序中可能出现的错误。通过继承标准库中的异常类,你可以创建具有特定语义的异常类型,使代码更具可读性和可维护性。
继承标准异常类
C++标准库定义了一套异常类,位于exception头文件中。最基础的是std::exception,其他常用派生类包括std::runtime_error、std::invalid_argument等。
自定义异常推荐继承std::runtime_error或其他标准异常,而不是直接继承std::exception,因为前者支持携带错误信息。
示例:
立即学习“C++免费学习笔记(深入)”;
#include#include class MyException : public std::runtime_error { public: explicit MyException(const std::string& message) : std::runtime_error(message) {} };
添加自定义信息和行为
你可以在自定义异常中加入额外的数据成员或方法,用于传递更详细的错误上下文。
例如:
class FileOpenException : public std::runtime_error {
std::string filename;
int error_code;
public:
FileOpenException(const std::string& file, int code)
: std::runtime_error("Failed to open file: " + file),
filename(file), error_code(code) {}
const std::string& getFilename() const { return filename; }
int getErrorCode() const { return error_code; }
};
这样在捕获异常时,可以获取具体出错的文件名和错误码。
抛出和捕获自定义异常
使用throw关键字抛出异常实例,用try-catch块捕获并处理。
示例:
立即学习“C++免费学习笔记(深入)”;
try {
throw FileOpenException("config.txt", 404);
}
catch (const FileOpenException& e) {
std::cout << "Error: " << e.what() << std::endl;
std::cout << "File: " << e.getFilename() << std::endl;
std::cout << "Code: " << e.getErrorCode() << std::endl;
}
catch (const std::exception& e) {
std::cout << "Standard exception: " << e.what() << std::endl;
}
注意:捕获时应先捕获派生类异常,再捕获基类,避免被覆盖。
基本上就这些。继承标准异常、添加必要信息、合理抛出与捕获,就能构建清晰的错误处理机制。










