Nested try…catch inside C++ exception handler?

后端 未结 3 1763
执念已碎
执念已碎 2021-01-04 01:38

The code I want to execute in my exception handler may itself throw an exception.

Is the follow structure legal C++? If yes, are there any downsides?



        
3条回答
  •  Happy的楠姐
    2021-01-04 01:52

    It's a perfectly valid way to code.

    #include 
    using namespace std;
    
    
    
    int main(int argc, char* argv[])
    {
            try       //outer try{}
            {
                    try   //inner try{}
                    {
                        throw std::runtime_error("Demo");
                    }
                    catch (std::runtime_error& e)
                    {
                        std::cerr << "Inner Exception-Handler: " << e.what() << std::endl;
                        throw;
                    }
            }
            catch (std::exception& e)
            {
                std::cerr << "Outer Exception-Handler: " << e.what() << std::endl;
            }
    
        return 0;
    }
    

提交回复
热议问题