Thursday, May 18, 2006

C++: Accessing Exception Data in a Generic catch(...)

You have a generic C++ exception handler using catch(...) and you need to find the type of exception being thrown. Unlike Java and .NET, the generic handler is not accepting any argument. Roger Orr's article shows how to get the exception data on a Microsoft compiler.

Here is the code (with the author's permission):
// Called from within a catch handler to log a string from the current exception
void logException()
{
std::string error;
try
{
// re-throw the exception to have another look at it
throw;
}
catch ( std::exception & ex )
{
error = ex.what();
}
catch ( CException * pEx )
{
char szMsg[255];
pEx->GetErrorMessage(szMsg, sizeof( szMsg ));
pEx->Delete();
error = szMsg;
}
// etc etc
catch ( const char *pStr )
{
error = pStr;
}
catch (...)
{
// Search me...
throw;
}
std::cerr << "Uncaught exception: " << error << std::endl;
}

No comments:

About Me

My photo
C/C++ Programmer doing CAD on Windows. Some web development experience. Bangalorean.

Blog Archive

Labels