On Trying to Log an Exception as it Leaves your Scope -- Raymond Chen

RaymondChen_5in-150x150.jpgA customer attempted to log exceptions using a scope_exit handler, expecting it to capture and process exceptions during unwinding. However, they encountered crashes because ResultFromCaughtException requires an actively caught exception, which isn’t available during unwinding—leading to an unexpected termination.

On Trying to Log an Exception as it Leaves your Scope

by Raymond Chen

From the article:

A customer wanted to log exceptions that emerged from a function, so they used the WIL scope_exit object to specify a block of code to run during exception unwinding.

void DoSomething()
{
    auto logException = wil::scope_exit([&] {
        Log("DoSomething failed",
            wil::ResultFromCaughtException());
    });

    ⟦ do stuff that might throw exceptions ⟧

    // made it to the end - cancel the logging
    logException.release();
}

They found, however, that instead of logging the exception, the code in the scope_exit was crashing.

They debugged into the Result­From­Caught­Exception function, which eventually reaches something like this:

try
{
    throw;
}
catch (⟦ blah blah ⟧)
{
    ⟦ blah blah ⟧
}
catch (⟦ blah blah ⟧)
{
    ⟦ blah blah ⟧
}
catch (...)
{
    ⟦ blah blah ⟧
}

The idea is that the code rethrows the exception, then tries to catch it in various ways, and when it is successful, it uses the caught object to calculate a result code.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.