开发者

How can I determine the current exception in a catch (...) block? [duplicate]

开发者 https://www.devze.com 2022-12-20 20:59 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Determining exception type开发者_运维百科 after the exception is caught?
This question already has answers here: Closed 12 years ago.

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.


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;
}


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?


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.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消