Exception is not caught although it is included in catch statement - c++

I have this program written in C++ Builder 6. I didn't write all the code, just some of it. The language, however, is not C++ (as far as I'm aware) - it looks more like Delphi or Pascal. So that's why I included them all in the tags.
I have an int called Oversteering.
try
{
Oversteering=HoursCounter.ToInt();
}
catch(EConvertError &convertError)
{
Oversteering=0;
}
HoursCounter is an AnsiString, and it is in the form of an int.
Since this is the only try/catch statement in the whole code (that's not too good, I know), and I couldn't find any good example of such in Delphi/Pascal/???, I don't know if it's correctly written.
Well, I try to convert the string to an int. Sometimes I get this error:
That is, an exception called EConvertError has occurred.
So my question is: why is this exception NOT caught by the catch statement?

This error is shown by the debugger when running through the code,
if you run the exe and have the same situation the error message will not be shown to you
The exception is caught but the debugger is notifiying you regarding the error in the code
that is here
try
{
Oversteering=HoursCounter.ToInt();
}
since running in the debugger the ,your trying to convert (blankspace) '' to integer, the debugger will show the exception...but when running the exe, the debugger will set
Oversteering=0
check this from about.com
Break On Exceptions
When building a program with exception handling, you may not want Delphi to break on Exceptions. This is a great feature if you want Delphi to show where an exception has occurred; however, it can be annoying when you test your own exception handling.

As #PresleyDias explained, it is the debugger that is displaying the exception, not your app. The exception is being caught (you should be catching it by a const reference, though), but the debugger sees it before your app does, that's all. You can configure the debugger to ignore EConvertError, if you like.
A better solution is to avoid the exception in the first place. If you use AnsiString::ToIntDef() instead, you can remove the try/catch block completely:
Oversteering = HoursCounter.ToIntDef(0);
Alternatively, you can use TryStrToInt() instead:
if (!TryStrToInt(HoursCounter, Oversteering))
{
...;
}
If 0 is a valid value for your counter, use TryStrToInt():
if (TryStrToInt(HoursCounter, Oversteering))
{
// use Oversteering as needed, even zeros...
}
else
ShowMessage("Cannot convert HoursCounter to a valid integer!");
If 0 always represents an error, then use ToIntDef():
Oversteering = HoursCounter.ToIntDef(0);
if (Oversteering != 0)
{
// use Oversteering as needed, except zeros...
}
else
ShowMessage("Cannot convert HoursCounter to an acceptable integer!");

Related

Trying to catch exception in MFC's CString::Format

I am working with a C++ project (that I was not the author of) that has a lot of MFC string formatting functions. Unfortunately, stuff like %d and %s are very close together (including the location of letters d and s on the keyboard) that one can be transposed with another. So I may at times witness a code line as such:
CString s;
s.Format(L"Value v=%s", 100); //Should've been %d instead
This results in a hard crash of the process, that is very hard to locate & isolate in the final project. So I was thinking to wrap the Format function in my own override and catch the exception & log it before it is thrown as unhandled exception.
So I employed the following construct:
__try
{
//Do the Format function here
}
__except(1)
{
//Log the error, etc.
}
But unfortunately the construct above did not catch the exception from the first code chunk, so I got VS 2008 C++ debugger kick in and show this:
I then tried this:
try
{
//Do the Format function here
}
catch(int e)
{
//Do the logging
}
But that didn't catch it either.
So how can I catch that fault?
PS. And I have a second question. Is there an easy way to override an MFC function, like Format for instance?
MFC throws CException pointers, so you could try this:
try
{
// Do the Format function here
}
catch(CException* e)
{
// Do the logging then free the exception
if (m_bThrowExceptionAgain)
throw; // Do not delete e
else
e->Delete();
}
You have to delete the exception object once you have caught it as shown in the example. Also make sure you have C++ exceptions enabled in your compiler. See http://msdn.microsoft.com/en-us/library/0e5twxsh.aspx for more information.
As others have already said low-level exceptions (like access violations) are not the same as C++ exceptions. They fall under the term Structured Exception Handling and would require other means to catch, at least by default.
It's possible to change compiler settings (at least in Visual Studio) to make it wrap those exceptions into something that C++ try/catch statements can handle, but as I recall that loses the details of what the SEH exception was and where it came from.
One way or another you could probably get exceptions to work well enough to help track down these issues, but there is also another way: Use static code analysis.
While standard C++ compilers don't normally verify format/printf-style calls, there are various tools that will. In fact some recent versions/editions of Visual Studio come with a code analysis tool, although it may not have been available in VS 2008 which you mentioned. So it might be worthwhile for you to do some research and see if you can get a hold of some kind of code analysis tool which could then catch all the CString::Format mistakes during analysis/compile-time rather than run-time.
You can use _set_se_translator() to convert SEH exceptions like access violation to C++ exceptions which you can then catch with except().
Some sample code: http://www.codeproject.com/Articles/422/SEH-and-C-Exceptions-catch-all-in-one

Temporally disable first-chance exceptions

Is there a way of temporally disable first-chance exceptions in Visual C++?
Something like this:
void someFunc() {
disableFirstChanceExceptions();
try {
// some code
}
catch (std::exception& e) {
// some code
}
catch (...) {
// some code
}
enableFirstChanceExceptions();
}
I know what first-chance-exceptions are and how to use them.
The problem is, that I am distributing a DLL, in which exceptions are used.
Unfortunately if a customer is using a debugger with his program, he will notice my intern exceptions.
It is not that I want to hide them, it is more that I want to get rid of these support questions.
Your code throws exceptions.
Your customers insist on running debuggers against your code, and explicitly configure it to break on first-chance exceptions.
You have basically two options:
don't throw exceptions, or
ignore when your customer is being stupid. What your code does internally is none of their business as long as it works as intended.
I'd suggest the latter. If they have a problem with exceptions being thrown and caught inside third-party code, they'll find themselves unable to use a lot of libraries. They'll need to grow up and start acting like they know what they're doing.
First chance exceptions are not something that can be turned on and off in your code (speaking only about windows, vs, c++ chain, not familiar with other platforms). This is construct is built into the run time system to make debugging possible. The debugger can be configured to ignore some or all first chance exceptions. You can use ctrl + alt + e to bring up the VS debugger's exception handling behavior menu. This will allow clients debugging to filter what the want caught by the debugger.

c++ non-fatal exception handling

I was told in a comment in another thread that I should be using exceptions whenever anything out of the ordinary happens, even if it isn't fatal to the script. This came up as I was using constructs akin to the following:
return err("File could not be loaded");
which would print the error to the screen, and return false, terminating the instruction processing. It was suggested that this would be better handled with exceptions.
The trouble is that the program is, for all intents and purposes, a language interpreter, controlled through a console, which means that any time a command is input incorrectly, or there is a bug in the interpreted code, an error needs to be displayed.
Besides the fact that these issues seem to minor to be processed as exceptions, how should it be implemented? How can a try block be used to control processing paths? For example, currently my code looks as follows:
if(!validate(code))
return false; //the validate function already having output the error
else
process(code);
How should I ensure that process(code) only executes if validate(code) succeeds? Should I just return false; from the function in the catch block? This would seem to return to the original issue of using return values to handle exceptional events. It seems to me that the fundamental problem is that the issues aren't exceptions at all, but I defer to those with more experience than I.
If an operation may - by design - either succeed or fail, and both of those are common, it might be most clear to structure your command flow in such way that errors are checked "explicitly", like in boolean value of "validate" function.
Exceptions come in handy when you don't want to disturb your regular control flow with error checking and want to move the checking somewhere else, maybe some function call levels above.
Your situation sounds like you don't really need exceptions. If your code looks clean without them, stay with it.
The idea of exceptions is you wouldn't need something like a separate "validate" step. Whenever "process" gets to a point where something's broken, throw an exception.
If you did need a separate validation step for some reason, then it'd look like
validate(code);
process(code);
Validate would throw an exception on failure, in which case process would never be reached.
try
{
validate(code);
process(code);
}
catch(...)
{
return false;
}
return true;
Assuming that validate throws, process won't happen.
Maybe you want your top-level loop to look something like this:
while (!quit) {
try {
process_command_line_input();
}
catch (const std::exception& ex) {
std::cerr << "Error: " << ex.what() << std::endl;
}
}
So, process_command_line_input() gets the next line of input and does whatever it does. If any error is detected, an exception is thrown, the top level loop displays it, and then goes on to the next input line.
The issue is that you have your function set up to use a return code. You can't just drag and drop exceptions in when your code is already set up with return values.
The correct way to do it is like
std::string code;
// input into code
try {
validate(code);
process(code); // Throws an exception.
}
catch(std::runtime_error& except) {
std::cout << except.what();
// recover from here.
}
There is no one correct answer.
It is highly dependent on the code and the situation:
In your situation the simple code above (if it is withing my own class) then error codes are fine:
class MyClass
{
public:
void processesValidCodesOrIgnore(int code)
{
if (validate(code))
{
processesCode(code);
}
}
private:
bool validate(int);
void processesCode(int);
};
As the validate method is private I know its result will always be checked and not ignored so its very easy to just use error codes in this situation.
On the other hand if validate was public I would definately consider using exceptions (depending on usage). As this would force the caller to actively check for problems rather than silently ignoring them.

Debugging causing exceptions?

I was getting bad data from an application I was writting using C++ in Visual Studio 2k3 so I decided to debug it. Then I found it was throwing an exception but one I can't track down.
Then I placed some try/catch blocks and low and behold, when I don't debug there is no exception. That is, I have code that looks like this:
std::vector<MyClass*> ListOfStuff;
.
.
.
try
{
.
.
.
const MyClass * localPointer = ListOfStuff[i]; //This is where the exception occurs
.
.
}
catch (...)
{
int x = 0; //place break here
}
So if I step through the code line by line I'll get an exception and shot to the catch. But if I just let it run with a breakpoint inside the catch nothing happens. Using an iterator has the same behavior. And I can successfully check the size of the vector so I know I'm within the bounds.
Can anyone tell me what's going on? If it matters I'm using some standard windows libraries and openGL.
You can try placing a
DebugBreak();
call in the catch clause. If the app is running in the debugger, it should get control. If it's not running in the debugger you should get an opportunity to attach the "Just in Time" debugger (which is usually Visual Studio if you have that installed).
I'm referring to VS2005 but it should be applicable in your case. If you access the IDE Debug > Exceptions.. menu item you can specify the exception types that the IDE debugger should break on when thrown which should cause you to see the line the exception was raised by when single stepping through the application.
You may need to play around with what types to catch (some 1st chance exceptions are not actually problems) but it will be helpful in identifying the point the exception is raised.
Is the exception an ASSERT? These may get compiled out at compile time or otherwise throw an assertion.
For example, you could have
#ifdef DEBUG
#define ASSERT(cond) if (cond) throw CDebugAssertionObj;
#else
#define ASSERT(cond)
#endif
If you're using a good IDE that allows conditional breakpoints (such as, "break here if i == 5"), then it's possible the condition itself is causing the exception.
Had that one for while... my head hurt when I found it.
Is that code part of a class method, and is ListOfStuff a member of the class? If so, check to make sure that your this pointer is valid.

Finding out the source of an exception in C++ after it is caught?

I'm looking for an answer in MS VC++.
When debugging a large C++ application, which unfortunately has a very extensive usage of C++ exceptions. Sometimes I catch an exception a little later than I actually want.
Example in pseudo code:
FunctionB()
{
...
throw e;
...
}
FunctionA()
{
...
FunctionB()
...
}
try
{
Function A()
}
catch(e)
{
(<--- breakpoint)
...
}
I can catch the exception with a breakpoint when debugging. But I can't trace back if the exception occurred in FunctionA() or FunctionB(), or some other function. (Assuming extensive exception use and a huge version of the above example).
One solution to my problem is to determine and save the call stack in the exception constructor (i.e. before it is caught). But this would require me to derive all exceptions from this base exception class. It would also require a lot of code, and perhaps slow down my program.
Is there an easier way that requires less work? Without having to change my large code base?
Are there better solutions to this problem in other languages?
You pointed to a breakpoint in the code. Since you are in the debugger, you could set a breakpoint on the constructor of the exception class, or set Visual Studio debugger to break on all thrown exceptions (Debug->Exceptions Click on C++ exceptions, select thrown and uncaught options)
If you are just interested in where the exception came from, you could just write a simple macro like
#define throwException(message) \
{ \
std::ostringstream oss; \
oss << __FILE __ << " " << __LINE__ << " " \
<< __FUNC__ << " " << message; \
throw std::exception(oss.str().c_str()); \
}
which will add the file name, line number and function name to the exception text (if the compiler provides the respective macros).
Then throw exceptions using
throwException("An unknown enum value has been passed!");
There's an excellent book written by John Robbins which tackles many difficult debugging questions. The book is called Debugging Applications for Microsoft .NET and Microsoft Windows. Despite the title, the book contains a host of information about debugging native C++ applications.
In this book, there is a lengthy section all about how to get the call stack for exceptions that are thrown. If I remember correctly, some of his advice involves using structured exception handling (SEH) instead of (or in addition to) C++ exceptions. I really cannot recommend the book highly enough.
Put a breakpoint in the exception object constructor. You'll get your breakpoint before the exception is thrown.
There is no way to find out the source of an exception after it's caught, unless you include that information when it is thrown. By the time you catch the exception, the stack is already unwound, and there's no way to reconstruct the stack's previous state.
Your suggestion to include the stack trace in the constructor is your best bet. Yes, it costs time during construction, but you probably shouldn't be throwing exceptions often enough that this is a concern. Making all of your exceptions inherit from a new base may also be more than you need. You could simply have the relevant exceptions inherit (thank you, multiple inheritance), and have a separate catch for those.
You can use the StackTrace64 function to build the trace (I believe there are other ways as well). Check out this article for example code.
Here's how I do it in C++ using GCC libraries:
#include <execinfo.h> // Backtrace
#include <cxxabi.h> // Demangling
vector<Str> backtrace(size_t numskip) {
vector<Str> result;
std::vector<void*> bt(100);
bt.resize(backtrace(&(*bt.begin()), bt.size()));
char **btsyms = backtrace_symbols(&(*bt.begin()), bt.size());
if (btsyms) {
for (size_t i = numskip; i < bt.size(); i++) {
Aiss in(btsyms[i]);
int idx = 0; Astr nt, addr, mangled;
in >> idx >> nt >> addr >> mangled;
if (mangled == "start") break;
int status = 0;
char *demangled = abi::__cxa_demangle(mangled.c_str(), 0, 0, &status);
Str frame = (status==0) ? Str(demangled, demangled+strlen(demangled)) :
Str(mangled.begin(), mangled.end());
result.push_back(frame);
free(demangled);
}
free(btsyms);
}
return result;
}
Your exception's constructor can simply call this function and store away the stack trace. It takes the param numskip because I like to slice off the exception's constructor from my stack traces.
There's no standard way to do this.
Further, the call stack must typically be recorded at the time of the exception being thrown; once it has been caught the stack has unrolled, so you no longer know what was going on at the point of being thrown.
In VC++ on Win32/Win64, you might get usable-enough results by recording the value from the compiler intrinsic _ReturnAddress() and ensuring that your exception class constructor is __declspec(noinline). In conjunction with the debug symbol library, I think you could probably get the function name (and line number, if your .pdb contains it) that corresponds to the return address using SymGetLineFromAddr64.
In native code you can get a shot at walking the callstack by installing a Vectored Exception handler. VC++ implements C++ exceptions on top of SEH exceptions and a vectored exception handler is given first shot before any frame based handlers. However be really careful, problems introduced by vectored exception handling can be difficult to diagnose.
Also Mike Stall has some warnings about using it in an app that has managed code. Finally, read Matt Pietrek's article and make sure you understand SEH and vectored exception handling before you try this. (Nothing feels quite so bad as tracking down a critical problem to code you added help track down critical problems.)
I believe MSDev allows you to set break points when an exception is thrown.
Alternatively put the break point on the constructor of your exception object.
If you're debugging from the IDE, go to Debug->Exceptions, click Thrown for C++ exceptions.
Other languages? Well, in Java you call e.printStackTrace(); It doesn't get much simpler than that.
In case anyone is interested, a co-worker replied to this question to me via email:
Artem wrote:
There is a flag to MiniDumpWriteDump() that can do better crash dumps that will allow seeing full program state, with all global variables, etc. As for call stacks, I doubt they can be better because of optimizations... unless you turn (maybe some) optimizations off.
Also, I think disabling inline functions and whole program optimization will help quite a lot.
In fact, there are many dump types, maybe you could choose one small enough but still having more info
http://msdn.microsoft.com/en-us/library/ms680519(VS.85).aspx
Those types won't help with call stack though, they only affect the amount of variables you'll be able to see.
I noticed some of those dump types aren't supported in dbghelp.dll version 5.1 that we use. We could update it to the newest, 6.9 version though, I've just checked the EULA for MS Debugging Tools -- the newest dbghelp.dll is still ok to redistribute.
I use my own exceptions. You can handle them quite simple - also they contain text. I use the format:
throw Exception( "comms::serial::serial( )", "Something failed!" );
Also I have a second exception format:
throw Exception( "comms::serial::serial( )", ::GetLastError( ) );
Which is then converted from a DWORD value to the actual message using FormatMessage. Using the where/what format will show you what happened and in what function.
By now, it has been 11 years since this question was asked and today, we can solve this problem using only standard C++11, i.e. cross-platform and without the need for a debugger or cumbersome logging.
You can trace the call stack that led to an exception
Use std::nested_exception and std::throw_with_nested
This won't give you a stack unwind, but in my opinion the next best thing.
It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.
It will, however, require that you insert try/catch statements at the functions you wish to trace (i.e. functions without this will not appear in your trace).
You could automate this with macros, reducing the amount of code you have to write/change.
Since you can do this with any derived exception class, you can add a lot of information to such a backtrace!
You may also take a look at my MWE on GitHub, where a backtrace would look something like this:
Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"