3

I'm currently following C++ core guidelines setting all destructors in my code to be noexcept. Some of my destructors may potentially throw exceptions - in that case I would like the program to crash and provide me with details on what caused the crash. Setting the noexcept specifier on the destructor will call std::terminate() which in turns invoke the default terminate_handler. The default terminate_handler will print the exception which was fired inside the destructor. This is great in the case in which the throwing destructor was not called while another exception was being thrown. In that case I would like the terminate_handler to print both exceptions so I can know what triggered the error handling path in the first place.

The problem is I can't seem to find a way in the standard library to get the uncaught exception. There's a std::current_exception() function which gets the exception being handled and std::uncaught_exceptions() which only gets the number of uncaught exception. I would like to get an std::exception_ptr or something to the uncaught exceptions. Is that possible?

smichak
  • 4,716
  • 3
  • 35
  • 47

1 Answers1

0

See: https://www.danielseither.de/blog/2013/12/globally-handling-uncaught-exceptions-and-signals-in-c/

std::exception_ptr exptr = std::current_exception();
try {
    std::rethrow_exception(exptr);
}
catch (std::exception &ex) {
    std::fprintf(stderr, "Terminated due to exception: %s\n", ex.what());
}
Rian Quinn
  • 1,766
  • 12
  • 22
  • OP said `std::current_exception` is not enough for him since it will only provide one exception. – LanYi Oct 30 '21 at 17:35
  • You just run this until the total number of pending exceptions has been caught. – Rian Quinn Oct 31 '21 at 21:35
  • In general BTW, you should not let std::terminate execute. If you label a function as noexcept, you should be wrapping all of the code in that function in a catch all and handling the exception there, so although the code above will work fine, in general, letting exceptions stack like that and relying on std::terminate is a bad idea. – Rian Quinn Oct 31 '21 at 21:39