Reputation: 68698
Is there any way in gcc/linux to have a user-defined function called immediately after any C++ throw statement executes, but before the stack is unwound to the catch? (I want to capture a stacktrace.)
(In gdb I can write catch throw
. Anyway to do that programmatically short of a compiler extension?)
Upvotes: 1
Views: 278
Reputation: 16680
at your throwing site you can do this:
try { throw 13; }
catch (...) { print_stack_trace(); rethrow;}
Of course, if you want this everywhere, then you'll need some automated editing to put it there (or a macro like this): untested code
#define THROW(x) do { \
try {throw(x);} \
catch(...) { print_stack_trace(); rethrow;} \
} while(false)
or even simpler:
#define THROW(x) do { \
print_stack_trace(); \
throw(x); \
} while(false)
Upvotes: 0
Reputation: 26166
If you are using libstdc++
, you could override __cxa_throw()
.
For instance:
#include <cstring>
void __cxa_throw(void *, void *, void (*)(void *)) {
std::puts("bad luck");
}
int main() {
throw 13;
}
Upvotes: 2