How can I catch a divide-by-zero error (and not other errors; and to be able to access exception information) in Visual Studio 2008 C++?
I tried this:
You can either use structured exception handling (using __try etc.) or you can install a structured exception handler translator: _set_se_translator
Both of these are operating system specific.
Why not check for this before? The performance will be trivial for a simple j == 0
compared to context-switching for exception 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.
Try the following code:
try
{
const int j=0;
if (j == 0) { throw std::exception("j was 0"); }
const int i= 1/j;
}
catch(std::exception& e)
{
printf("%s %s\n", e.what());
}
catch(...)
{
printf("generic exception");
}
Of course, if you're OK doing this without exceptions, you could do:
const int j = 0;
if (j == 0)
{
/* do something about the bad pre-condition here */
}
else
{
const int i = 1 / j;
}
Edit in response to clarification: you'll have to figure out what input it is that you're handing the third party that causes them to divide by zero before-hand, and handle that before ever calling their function.
You can use try-except Statement. But, don't forget that you need to set it for each thread.