Reputation: 6584
The high level problem I'm trying to solve is to log stacktrace for every exception that is being thrown from [legacy] code. The solution I'm trying to find an alternative to is logging stacktrace from the exception constructor. Indeed, this works only for custom type of exceptions, and that requires wrapping all other primitives just for the purpose of substituting standard exceptions with custom ones.
So, to log call stack I need to do it before unwinding the stack. This can be done from the exception constructor, or from the terminate handler. The latter approach allows logging call stack, but will terminate the program, and that may be undesirable. Here is an example: a GUI application that shall not crash, but log/display the stacktrace, and allow the user to perform another operation. But not crashing means catching exceptions, and that means stack unwinding...
Is there any good way to combine exception handling with the code that can be executed like a terminate
handler (right after the exception is thrown)? For example, if the terminate handler was not declared [[noreturn]] noexcept
, I could have logged call stack, and then substitute the type of exception, making it recoverable:
/*[[no-noreturn]]*/ void onTerminate() /*no-noexcept*/ {
std::string stackDescription = ...
throw MyExceptionToBeCaughtInGUI(std::move(stackDescription));
}
int main() {
std::set_terminate(&onTerminate);
try {
// run...
}
catch(const MyExceptionToBeCaughtInGUI &e) {
displayCallStack(e.stackDescription);
}
}
For sure this code doesn't work. What can be done instead?
Update: the answer to this question doesn't provide a solution for my case. I know how to log stack when I'm terminating the program, but the essential part of my question is how to do that without termination. Please de-duplicate.
Upvotes: 0
Views: 56