我正在编写一些将抛出自定义异常的新代码 - 我想包含一个错误字符串和一个状态代码。哪个类应该是异常派生的? 标准::异常
? std::runtime_error
?还有其他需要担心的“问题”吗?我正在考虑以下内容:
class MyException : public std::exception(?)
{
public:
enum Status
{
ERROR_FOO,
ERROR_BAR,
...
};
MyException(const std::string& error, Status code) :
error_(error), code_(code)
{
...
}
virtual const char* what() const
{
return error_.c_str();
}
Status code() const
{
return code_;
}
private:
std::string error_;
Status code_;
};
然后在代码中:
throw MyException("Ooops!", MyException::ERROR_BAR);
最佳答案
Boost 在 error and exception 上有一个很棒的文档handling 讨论了常见的陷阱以及如何正确地从 std::exception(s) 继承。
关于c++ - 滚动我自己的异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/336475/