Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching all exceptions and logging information

I am a Java programmer working with C++ code, and need some help with exception handling.

I have code in the following structure:

try{
...
}
catch( ... ) 
{
    log("Exception occurred");
}

An exception is occurring, but the try block is really massive and debugging is not an option, so I need to minimally modify the code to give me relevant info on the exception.

So I added the following catch block before the existing catch block (working with my Java knowledge and referring to C++ guides):

catch(exception e)
{
    log(e.what());
}

However, I am still getting the old message - "Exception occurred". The code in try block contains a lot of low level functions like strncpy, memcpy etc.

Why is this catch block not working as expected? What can I do to get information on the exception that is occurring and on which line, similar to the stack trace that Java so easily gives.

like image 489
Shailesh Tainwala Avatar asked May 10 '12 07:05

Shailesh Tainwala


3 Answers

First, you should catch by reference (generally const), so your new catch block should read:

try {

} catch(std::exception const& e) {
    log(e.what());
} catch(...) {
    log("Exception occurred");
}

Second, in C++ you may throw any value. Even of type int. If your codebase include such unsavvy throw statements, I pity you.

Since you come from Java, I would check if you mistakenly used a throw new XXXX which would throw a pointer (to a dynamically allocated value) instead of a value. The new is unnecessary in C++.

like image 109
Matthieu M. Avatar answered Oct 12 '22 10:10

Matthieu M.


Probably because those exceptions are not derived from exception class. In C++ any type can be an exception, for example string, int, etc. Anyway if you want to catch exception you should probably catch a reference to the exception &.

like image 42
Jagger Avatar answered Oct 12 '22 10:10

Jagger


You will have to debug and determine if the exception is an C++ exception.
Note that divide by 0 etc are runtime exceptions not supported by C++, so it can be anything literally.

A catch-all handler will only catch valid C++ exceptions not all exceptions(which can be plenty).

like image 35
Alok Save Avatar answered Oct 12 '22 12:10

Alok Save