Nested try…catch inside C++ exception handler?

后端 未结 3 1769
执念已碎
执念已碎 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: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!

提交回复
热议问题