如何在C ++中模拟内部异常

Siv*_*ran 6 c++ exception

基本上我想在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之后仍然可以生存?

Hrv*_*eša 3

您还应该查看boost 异常,以获取包装的替代解决方案。