Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/137.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 正在捕获std::异常和错误\u状态_C++_Exception_Std - Fatal编程技术网

C++ 正在捕获std::异常和错误\u状态

C++ 正在捕获std::异常和错误\u状态,c++,exception,std,C++,Exception,Std,在我的代码中,我使用我定义的BasicException enum class MyError { ERROR_1, ERROR_2 }; class BasicException { public: BasicException(MyError err): _err(err) {} get_error() const {return _err;} private: MyError _err; } 问题是,我被告知BasicException应该继承自

在我的代码中,我使用我定义的BasicException

enum class MyError {
    ERROR_1,
    ERROR_2
};

class BasicException
{
public:
    BasicException(MyError err): _err(err) {}
    get_error() const {return _err;}
private:
    MyError _err;
}
问题是,我被告知BasicException应该继承自std::exception。但是,当我捕获const std::exception&e时,我将无法检索特定错误的MyError。那么它有什么好处呢


我不确定什么是最佳解决方案-但如果std::exception有一个接收错误值的构造函数,它可能会解决它。

如果您想专门捕获BasicException,请先像这样捕获它:

try
{

}
catch( BasicException& be )
{
    // your exception here
}
catch( std::exception& e )
{
    // other exceptions here
}
如果您想捕获所有异常,包括您的异常,那么如果BasicException继承了std::exception,那么:

try
{

}
catch( std::exception& e )
{
    // all exceptions here
}

您仍然可以捕获std::exception的子类,但我没有抓住要点。我没有做任何改变。我仍然需要分别捕获我的BasicException和std::exception。从std::exception继承的要点是,如果调用方不期望您的特定异常,他们仍然可以尝试捕获std::exception,仍然捕获异常并从中获得有用的信息。