Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested try...catch inside C++ exception handler?

Tags:

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?

try
{
    // ...
}
catch (const E&)
{
    try
    {
        // ...
    }
    catch (const F&)
    {

    }
}
like image 576
paperjam Avatar asked Jan 03 '12 11:01

paperjam


People also ask

Can you nest a try block inside another try block in C++?

If the exception thrown from func2() in the inner try block is type_err , the program skips out of both try blocks to the second catch block without invoking func3() , because no appropriate catch block exists following the inner try block. You can also nest a try block within a catch block.

Can try catch be nested?

Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.

How do you resolve a nested try catch?

How to Avoid the Nesting? Extracting the nested part as a new method will always work for any arbitrarily nested Try-Catch-Finally block. So this is one trick that you can always use to improve the code.

Can we use try and catch for exception handling?

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.


2 Answers

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!

like image 177
Dietmar Kühl Avatar answered Oct 07 '22 07:10

Dietmar Kühl


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

like image 27
ronag Avatar answered Oct 07 '22 07:10

ronag