tags:

views:

144

answers:

2

I was just wondering if a system exception like say divide by zero actually "throws" something to the application. Would it be possible to catch this somehow by default?.

i mean we can define a custom divide fn which checks for null divisor and throws an exception, but just thought it would be nice if this exception was thrown by default

//say I do this
int i;
try
{
i /= 0; // My compiler (gcc) did warn abt the divide by zero :-)
}
catch (...)
{
// Can we get here  for this case?
}
+3  A: 

This is OS-dependent. You can do it in Visual C++ code on Windows - catch(...) will also catch so-called structured exceptions that include divisions by zero, access violations, etc., but not in gcc-compiled code on Linux.

sharptooth
The key observation here is that dividing by 0 is undefined behaviour as far as the C++ standard is concerned. This means individual implementations can do what they like - interrupt the process with a signal, throw an exception, phone your boss and tell him you can't code for toffee, whatever.
Steve Jessop
For Windows you could use SetUnhandledExceptionFilter to install an handler which in turn could throw C++ exceptions, e.g. derived from std::exception.
ur
You need to turn on /EHa to catch divide by zero, etc in Visual C++:http://msdn.microsoft.com/en-us/library/1deeycx5%28VS.80%29.aspx
Rob K
Thanks guys.. I didn't know the fact that this one was undefined in C++.
+1  A: 

The C++ Standard does not say that divide by zero throws an exception - it says that it is undefined behaviour.

Also, when you say:

i /= 0; // My compiler (gcc) did warn abt the divide by zero :-)

the compiler can only give the warning if the thing you divide by is a constant.

anon