On 19 Feb 2007 13:10:31 -0800,
fi*******@gmail.com wrote:
>Exception Catching difference between VC++ and C#
In C# I have this:
try
{
int x, y, z;
x = 20;
y = 0;
z = x / y;
}
catch
{
Console.WriteLine("oops !");
}
And it nicely catches whatever error happens inside the try block.
But now in C++ I have this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
try
{
int x, y, z;
x = 20;
y = 0;
z = x / y;
}
catch(...)
{
cout << "Oops !";
}
}
And it blows. I get the windows dialog that tells me about sending the
error to Microsoft.
Why ?
In C++, division by zero is undefined, and you should not expect any
particular treatment of the error. In Windows, integer division by zero
causes a structured exception, and VC++ allows you to catch it directly
with __try/__except or translate it into a C++ exception with
_set_se_translator. The latter requires you to compile with /EHa, and then
you will be able to catch it in catch(...). To understand why it's bad to
indiscriminately catch structured exceptions as C++ exceptions, see:
http://members.cox.net/doug_web/eh.htm
The C# language defines division by zero to throw
System.DivideByZeroException, and you can achieve much the same effect in
C++ by using _set_se_translator and turning EXCEPTION_INT_DIVIDE_BY_ZERO
into a C++ exception. Because you will also have to use /EHa, you should
stay away from catch(...) for the reasons given in my article. My
preference is to test for a zero denominator in the rare cases in which it
can occur. (For floating point, however, I might prefer to check the FPU
status word at the end of a calculation.)
--
Doug Harrison
Visual C++ MVP