How to simulate inner exception in C++

前端 未结 6 1590
逝去的感伤
逝去的感伤 2021-01-02 19:06

Basically I want to simulate .NET Exception.InnerException in C++. I want to catch exception from bottom layer and wrap it with another exception and throw again to upper la

6条回答
  •  渐次进展
    2021-01-02 19:26

    //inversion of the problem :)
    struct base_exception : public std::exception
    {
        std::list snowball;
    
        base_exception() { }
        void add(base_exception* e) { snowball.push_back(e); }
    };
    
    void func2()
    {
        func2_exception e;
        e.add(new func2_exception());
        throw e;
    }
    
    void func1()
    {
        try
        {
            func2();
        }
        catch(base_exception& e)
        {
            e.add(new func1_exception());
            throw e; 
        }
    }
    int main(void)
    {
        try
        {
            func1();
        }
        catch(base_exception& e)
        {
            std::cout << "Got exception" << std::endl;
            //print info in the direct order of exceptions occurence
            foreach(base_exception* exception, e.snowball)
            {
                  std::cout << exception->what();
                  std::cout << "next exception was:" << std::endl;
            }
        }
    }
    

    hmmmm...

提交回复
热议问题