How can I determine the current exception in a cat

2019-01-20 09:45发布

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.

4条回答
Evening l夕情丶
2楼-- · 2019-01-20 10:12

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.

查看更多
家丑人穷心不美
3楼-- · 2019-01-20 10:22

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;
}
查看更多
叼着烟拽天下
4楼-- · 2019-01-20 10:31

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?

查看更多
等我变得足够好
5楼-- · 2019-01-20 10:35

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;
}
查看更多
登录 后发表回答