Reputation: 6507
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.
Upvotes: 5
Views: 8466
Reputation: 300349
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++.
Upvotes: 6
Reputation: 206636
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).
Upvotes: 2
Reputation: 10522
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 &
.
Upvotes: 3