How to catch divide-by-zero error in Visual Studio 2008 C++?
C++ does not handle divide-by-zero as an exception, per-se.
Quoting Stroustrup:
"low-level events, such as arithmetic overflows and divide by zero, are assumed to be handled by a dedicated lower-level mechanism rather than by exceptions. This enables C++ to match the behaviour of other languages when it comes to arithmetic. It also avoids the problems that occur on heavily pipelined architectures where events such as divide by zero are asynchronous."
"The Design and Evolution of C++" (Addison Wesley, 1994)
In any case, exceptions are never a replacement for proper precondition handling.
To catch divide by zero exceptions in Visual C++ try->catch (...) just enable /EHa option in project settings. See Project Properties -> C/C++ -> Code Generation -> Modify the Enable C++ Exceptions to "Yes With SEH Exceptions". That's it!
See details here: http://msdn.microsoft.com/en-us/library/1deeycx5(v=vs.80).aspx
Assuming that you can't simply fix the cause of the exception generating code (perhaps because you don't have the source code to that particular library and perhaps because you can't adjust the input params before they cause a problem).
You have to jump through some hoops to make this work as you'd like but it can be done.
First you need to install a Structured Exception Handling translation function by calling _set_se_translator()
(see here) then you can examine the code that you're passed when an SEH exception occurs and throw an appropriate C++ exception.
void CSEHException::Translator::trans_func(
unsigned int code,
EXCEPTION_POINTERS *pPointers)
{
switch (code)
{
case FLT_DIVIDE_BY_ZERO :
throw CMyFunkyDivideByZeroException(code, pPointers);
break;
}
// general C++ SEH exception for things we don't need to handle separately....
throw CSEHException(code, pPointers);
}
Then you can simply catch your CMyFunkyDivideByZeroException()
in C++ in the normal way.
Note that you need to install your exception translation function on every thread that you want exceptions translated.