samedi 28 mai 2022

re-throwing an exception from inside a terminatrion handler

Is the following code according to the standard ?

#include <iostream>
#include <exception>

using namespace std;

int main()
{
    auto terminationHandler = []()
    {
        try
        {
            rethrow_exception( current_exception() );
        }
        catch( exception const &exc )
        {
            cout << exc.what() << endl;
        }
        catch( ... )
        {
        }
    };
    set_terminate( terminationHandler );
    try
    {
        throw bad_alloc();
    }
    catch( ... )
    {
        terminate();
    }
}

This would be a nice aid for fatal situations that you still have some error-message.

I've got a function called exc_terminate() that's called like this:

exc_terminate( [&]() { ... do anything in local context ... } );

The lambda is executed within a try-catch-block and if an exception occurs the code terminates. I use this f.e. when a thread can't communicate with another thread because the synchronization-functions signalled a system_error.

Aucun commentaire:

Enregistrer un commentaire