基本上我想在C ++中模拟.NET Exception.InnerException。我想从底层捕获异常,并用另一个异常包装它,然后再次抛出到上层。这里的问题是我不知道如何将捕获的异常包装在另一个异常中。
struct base_exception : public std::exception
{
std::exception& InnerException;
base_exception() : InnerException(???) { } // <---- what to initialize with
base_exception(std::exception& innerException) : InnerException(innerException) { }
};
struct func1_exception : public base_exception
{
const char* what() const throw()
{
return "func1 exception";
}
};
struct func2_exception : public base_exception
{
const char* what() const throw()
{
return "func2 exception";
}
};
void func2()
{
throw func2_exception();
}
void func1()
{
try
{
func2();
}
catch(std::exception& e)
{
throw func2_exception(e); // <--- is this correct? will the temporary object will be alive?
}
}
int main(void)
{
try
{
func1();
}
catch(base_exception& e)
{
std::cout << "Got exception" << std::endl;
std::cout << e.what();
std::cout << "InnerException" << std::endl;
std::cout << e.InnerException.what(); // <---- how to make sure it has inner exception ?
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码清单中,我不确定在没有内部异常时如何初始化“ InnerException”成员。另外我不确定从func1抛出的临时对象是否即使在func2 throw之后仍然可以生存?
归档时间: |
|
查看次数: |
2753 次 |
最近记录: |