1

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?)

1

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

12 Comments

@MarshallClow Well, when you are there you can do whatever you want, including calling the proper thrower.
If it's somebody else's program, you can use LD_LIBRARY_PATH - I have an example here.
A better example here.
@AaronD.Marasco Indeed! Thanks for those links.
How would you call the "proper thrower" from within __cxa_throw? As Marshall said, once the function is complete I want the exception to be thrown and caught normally.
|
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.