RE: getting a stack trace from a c++ exception
From: Michael Böhnisch (MichaelBhnisch_at_discussions.microsoft.com)
Date: 11/09/04
- Next message: Pradeep Kumar: "RE: Form in a DLL ish"
- Previous message: Jochen Kalmbach: "Re: getting a stack trace from a c++ exception"
- In reply to: Chuck Bohling: "getting a stack trace from a c++ exception"
- Next in thread: Simon Trew: "Re: getting a stack trace from a c++ exception"
- Reply: Simon Trew: "Re: getting a stack trace from a c++ exception"
- Messages sorted by: [ date ] [ thread ]
Date: Tue, 9 Nov 2004 05:18:02 -0800
As Simon already pointed out, there is no built-in exception trace feature in
C++. However, if this is an important feature for you, you could adopt this
technique:
(note, I only present a rough outline here, there is much room for
improvement)
class Trace : public std::string {
public: Trace( const std::string& msg ) : std::string( msg ) {}
};
// derive exception classes from Trace or use it directly.
// Shape all involved methods and functions like this:
void foo()
{
try {
...
throw Trace( __FILE__ " : " __FUNCTION__ " : Mary had a little
lamb\n" );
...
}
catch ( Trace& trace ) {
trace += __FILE__ " : " __FUNCTION__ " : it's fleece was white as
snow\n";
throw;
}
}
Of course, introducing some preprocessor macros may greatly reduce the
efforts required. The predefined macro __LINE__ also may come in handy. Add
whatever you would like to be traced, eg function parameter values.
In your main() program you could add:
int main()
{
try {
...
foo();
...
}
catch ( Trace& trace ) {
trace += __FILE__ " : " __FUNCTION " : Mary shot it.\n";
std::cerr << "Stack trace for exception:\n" << trace;
}
return 0;
}
If now foo() throws a Trace object, the program will print something like:
Stack trace for exception:
dummy.cpp : foo : Mary had a little lamb,
dummy.cpp : foo : it's fleece as white as snow.
main.cpp : main : Mary shot it.
This technique is not well suited for large projects that already exist, but
may make life easier for things written from scratch. Also, if you introduce
some preprocessor macros, the whole thing is easily switched off, e.g. for
production code.
kind regards,
Michael Böhnisch
"Chuck Bohling" wrote:
> Anyone know how to get a stack trace from a C++ exception? I'm using
> unmanaged C++.
>
>
>
- Next message: Pradeep Kumar: "RE: Form in a DLL ish"
- Previous message: Jochen Kalmbach: "Re: getting a stack trace from a c++ exception"
- In reply to: Chuck Bohling: "getting a stack trace from a c++ exception"
- Next in thread: Simon Trew: "Re: getting a stack trace from a c++ exception"
- Reply: Simon Trew: "Re: getting a stack trace from a c++ exception"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|