主题
自定义异常类
在 C++ 中,除了标准库提供的异常类型,开发者还可以通过自定义异常类来更好地满足项目需求。自定义异常类通常继承自 std::exception
类,并重写 what()
方法返回异常的详细信息。通过自定义异常类,可以使得错误信息更加清晰,且更易于调试。
自定义异常类的基本结构
自定义异常类通常需要继承自 std::exception
,并重写 what()
方法来提供自定义的异常信息。
示例代码
cpp
#include <iostream>
#include <exception>
class MyException : public std::exception {
public:
// 构造函数,接受错误信息
MyException(const char* msg) : message(msg) {}
// 重写 what() 方法,返回错误信息
const char* what() const noexcept override {
return message;
}
private:
const char* message;
};
void testFunction() {
throw MyException("This is a custom exception!");
}
int main() {
try {
testFunction(); // 调用可能抛出自定义异常的函数
} catch (const MyException& e) {
std::cerr << "Caught custom exception: " << e.what() << std::endl;
}
return 0;
}
在这个例子中,MyException
是一个自定义的异常类,它继承自 std::exception
并实现了 what()
方法来返回错误信息。在 main()
函数中,我们捕获并处理了 MyException
类型的异常。
自定义异常类的扩展
你可以根据需要在自定义异常类中添加更多的功能,比如存储错误码、错误类型,甚至是错误发生的时间等信息。
带有错误码的自定义异常
cpp
#include <iostream>
#include <exception>
class ErrorCodeException : public std::exception {
public:
ErrorCodeException(int code, const char* msg) : errorCode(code), message(msg) {}
const char* what() const noexcept override {
return message;
}
int getCode() const {
return errorCode;
}
private:
int errorCode;
const char* message;
};
void testFunction() {
throw ErrorCodeException(404, "Resource not found");
}
int main() {
try {
testFunction();
} catch (const ErrorCodeException& e) {
std::cerr << "Caught exception with code " << e.getCode() << ": " << e.what() << std::endl;
}
return 0;
}
在这个例子中,ErrorCodeException
类除了包含错误信息外,还包含一个错误码,提供了更多的异常信息。
总结
- 自定义异常类通常继承自
std::exception
。 - 通过重写
what()
方法提供详细的错误信息。 - 可以扩展异常类以支持更多的自定义功能,如错误码、时间戳等。