Nested try…catch inside C++ exception handler?

后端 未结 3 1762
执念已碎
执念已碎 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条回答
  • 2021-01-04 01:41

    No, there are no downsides. That's the way you should do it.

    0 讨论(0)
  • 2021-01-04 01:50

    Actually, there is even an interesting technique for using nested try/catch-blocks: assume you have multiple functions which need effectively the same exception handling. Especially when wrapping another interface this is common scenario. In this case it is possible to catch all exceptions, call a function from the exception handler, and in this function rethrow the exception to implement the actual exception handling:

    void fancy_handler() {
        try {
            throw; // assumes that fancy_handler() is called from catch-clause
        } catch (std::runtime_error const& rt) {
            std::cout << "runtime-error: " << ex.what() << "\n";
        } catch (std::exception const& ex) {
            std::cout << "excption: " << ex.what() << "\n";
        } catch (...) {
            std::cout << "unknown exception\n";
        }
    }
    
    void foo() { try { do_foo(); } catch (...) { fancy_handler(); } }
    void bar() { try { do_bar(); } catch (...) { fancy_handler(); } }
    

    I just love avoiding duplicate [non-trivial] code!

    0 讨论(0)
  • 2021-01-04 01:52

    It's a perfectly valid way to code.

    #include <iostream>
    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;
    }
    
    0 讨论(0)
提交回复
热议问题