Search code examples
c++c++11try-catchc++14code-duplication

Do the same action at the end of the try block and all catch clocks in a try-catch statement


Is it a way to avoid code duplication (FinalAction function call in all catch blocks and in a try one)?

try
{
    // some actions including creation of new objects
    FinalAction();
}
catch (const Exception1& ex1)
{
    ProcessException1(ex1);
    FinalAction();
}
catch (const Exception2& ex2)
{
    ProcessException2(ex2);
    FinalAction();
}
// ...
catch (const ExceptionN& exN)
{
    ProcessExceptionN(exN);
    FinalAction();
}
catch (...)
{
    ProcessUnknownException();
    FinalAction();
}

Update: FinalAction() should be called before the destructors of the objects created in the try block. So simple solution like the following one doesn't work here.

try
{
    // some actions including creation of new objects
}
catch (const Exception1& ex1)
{
    ProcessException1(ex1);
}
catch (const Exception2& ex2)
{
    ProcessException2(ex2);
}
// ...
catch (const ExceptionN& exN)
{
    ProcessExceptionN(exN);
}
catch (...)
{
    ProcessUnknownException();
}
FinalAction();

Some more information about FinalAction: it doesn't throw and it doesn't clean any resources allocated in the try block.


Solution

  • The simplest thing to do is just call it after the try block.

    bool success = false;
    try
    {
        // some actions including creation of new objects
        FinalAction();
        success = true;
    }
    catch (const Exception1& ex1)
    {
        ProcessException1(ex1);
    }
    if (!success)
        FinalAction();
    

    However it's pretty dubious to be doing this instead of using a class to manage whatever resource you're cleaning up with FinalAction.