Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 561
Joshua Fox Avatar asked Feb 23 '10 17:02

Joshua Fox


People also ask

Can an exception be caught twice?

Bookmark this question. Show activity on this post. Java does not allow us to catch the exception twice, so we got compile-rime error at //1 .

What happens when there is a exception in the catch block itself?

Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.

Can exceptions be caught by multiple catch blocks in any order?

At a time only one exception occurs and at a time only one catch block is executed. All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.


1 Answers

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;
}
like image 195
Len Holgate Avatar answered Oct 30 '22 14:10

Len Holgate