views:

360

answers:

2

In the following C++ code, it should be impossible for ain integer division by zero to occur:

// gradedUnits and totalGrades are both of type int
if (gradedUnits == 0) {
    return 0;
} else {
    return totalGrades/gradedUnits; //call stack points to this line
}

however Visual Studio is popping up this error:

Unhandled exception at 0x001712c0 in DSA_asgn1.exe: 0xC0000094: Integer division by zero.

And the stack trace points to the line indicated in the code.

UPDATE: I may have just been doing something silly here. While messing around trying to get VS to pay attention to my debug breakpoints, I rebuilt the solution and the exception isn't happening any more. It seems likely to me that I was stopping in the middle of a debug session and resuming it, when I thought I was starting new sessions.

Thanks for the responses. Would it be appropriate here to delete my question since it's resolved and wasn't really what I thought it was?

It seems like VS might just do this with any integer division, without checking whether a divide by zero is possible. Do I need to catch this exception even though the code should never be able to throw it? If so, what's the best way to go about this?

This is for an assignment that specifies VS 2005/2008 with C++. I would prefer not to make things more complicated than I need to, but at the same time I like to do things properly where possible.

A: 

You should try going through this code with VS debugger, and see what are the actual values of those variables.

Glorphindale
A: 

It turns out this problem was caused by the code I originally had, which did not have the divide-by-zero check, shown here:

return totalGrades/gradedUnits;

The problem was that although I'd updated the code, I was actually still in the same debug session that threw the original error, so the program was still running on the old code and threw the error again every time I restarted it.

The problem was solved by rebuilding the solution, which forced a new debug session. Simply terminating the debug session and restarting it with a rebuild would have solved it too (I just hadn't noticed I was still in the session).

Dr. Monkey