views:

161

answers:

4

Possible Duplicate:
Determining exception type after the exception is caught?

Following up on this question , I'd like to print out the current exception in a catch(...) block -- just for logging. One answer there says that there is no standard way of doing this, but I don't like taking no for an answer :-)

current_exception is a function mentioned in various places on the web but apparently not well-supported. Any thoughts on this? After all, even C has errno.

Because it can be rethrown (with a simple *throw), the exception object must be available somehow.

I am using MSVS 9.0.

Edit: The conclusion seems to be that this is not possible.

A: 

You can turn on RTTI and use typeOf function. current_exception is purely stl function, and applies to stl exceptions only.
As a recommendation, use different catch(exctype) per exception type. This will make life a lot easier.

alemjerus
`catch(...)` doesn't give you an object to reference, so you can't know the type. And does RTTI work on POD types, such as int?
Mark Ransom
A: 

Like alemjerus already said: current_exception works only for stl exceptions. To get various stl errors you could also write:

#include <stdexcept>
#include <exception> //ecxeption (base class)
#include <new>       //bad_alloc
#include <typeinfo>  //bad_cast und bad_typeid
#include <ios>       //ios_base::failure    

...

try
{
  ...
}
catch(std::exception& e)
{
  cerr<<"Error: "<<e.what()<<endl;
}
hkda150
+2  A: 

Determine what exceptions can be thrown and use a set of catch handlers to catch a set of common base types that covers them all.


As for getting the exception object from catch(...), it can't be done portably and as far as I know, it can't be done at all using the Microsoft compiler or gcc. What makes you think the exception object still exists in a catch(...) handler anyway?

Joe Gauterin
>" What makes you think the exception object still exists in a catch(...) handler anyway?"Because it can be rethrown (with a simple "throw"), the object must be there somewhere.
Joshua Fox
If the catch(...) is the top level catch handler? The as-if rule would entitle the compiler to destroy the object whenever is/was convenient. I doubt that happens in practice though.
Joe Gauterin
+2  A: 

If you only care about exceptions that you know about when you're writing the code then you can write a handler that can deal with all 'known' exceptions. The trick is to rethrow the exception that you caught with catch(...) and then catch the various known exceptions...

So, something like:

try
{
 ...
}
catch(...)
{
   if (!LogKnownException())
   {
      cerr << "unknown exception" << endl;
   }
}

where LogKnownException() looks something like this:

bool LogKnownException()
{
   try
   {
      throw;
   }
   catch (const CMyException1 &e)
   {
      cerr << "caught a CMyException: " << e << endl;

      return true;
   }
   catch (const Blah &e)
   {
      ...
   }
   ... etc

   return false;
}
Len Holgate