For debugging purposes, I would like to log the exception that is causing stack unwinding that lead to destruction of specific object. Something like this (pseudocode, obviously insufficient and not working):
struct Test
{
~Test()
{
if (this_destructor_is_called_due_to_stack_unwinding)
std::cerr << "Blame my death on " << peek_at_current_uncaught_std_exception()->what();
}
};
int main()
{
try
{
Test t;
throw std::runtime_error("Oops...");
}
catch (...)
{
}
return 0;
}
The first part, this_destructor_is_called_due_to_stack_unwinding is possible: I can take a snapshot of std::uncaught_exceptions() in the constructor, and compare that stored value to the current value of std::uncaught_exceptions() in the destructor. Such technique ain't perfect, but it'll do what's expected for objects with automatic storage duration.
But the second part, peek_at_current_uncaught_std_exception() baffles me. std::current_exception() and related functions seem useless, because these lines aren't executed in an exception handler.
Is there any way I can access what() of a yet-uncaught exception (assuming it's an std:: exception) before it's caught by a matching exception handler, without interferring with its flow?
Edit: Minimal reproducible example is here: https://godbolt.org/z/T6M6ojbE9