I've been reading through the book Teach Yourself C++ In 21 Days , by Jesse Liberty and came across Exceptions and Errors chapter. The author uses this example:
int top = 10;
int bottom = 0;
try
{
cout << "top divided by bottom = ";
cout << (top / bottom) << endl;
}
catch(...)
{
cout << "something has gone wrong!" << endl;
}
And it works fine for him. The exception gets caught and the output is:
top divided by bottom = something has gone wrong!
I tried it myself and received the following error:
Unhandled exception at 0x0124152d in stuff.exe: 0xC0000094: Integer division by zero.
According to this thread, "Integer divide by zero is not an exception in standard C++." But Visual Studio is obviously throwing an exception here, though not catching it.
I tried defining top
and bottom
as double
, and I received the following output:
top divided by bottom = 1.#INF
So why the try catch
block isn't catching the integer division by zero
exception?
Use /EHa
to switch the exception-handling model, so non-C++ exceptions can be caught by try
-catch
.
Be aware that all asynchronous exceptions will be converted to synchronous if you do so, and you really don't want to catch most.
Thus, not recommended for general code.
As an aside, blindly catching all you can is a known anti-pattern, only catch what you really expect and can handle.
See here for __try
-__except
, which can always catch asynchronous exceptions: http://msdn.microsoft.com/en-us/library/s58ftw19.aspx
The book possibly overlooked to tell you that you have to compile with /EHa in effect. The default is /EHsc, it doesn't cause these SEH exceptions to be caught by catch (...).
Having catch (...) catch everything isn't very pretty. You would not want this to happen:
int* p = 0;
try {
int result = *p / 0;
std::cout << result << std::endl;
}
catch (...) {
std::cout << "Division by zero" << std::endl;
}
Not actually a division by zero fault, not good of course. The better mouse trap is to translate SEH exceptions to C++ exceptions. You do so by installing a callback that runs when an SEH exception occurs, like this:
#include <exception>
#include <eh.h>
#include <iostream>
class divisionbyzero_exception : public std::runtime_error {
public:
divisionbyzero_exception() : std::runtime_error("Division by zero") {}
};
void translate_seh_exception(unsigned int exceptioncode, struct _EXCEPTION_POINTERS* pExp) {
if (exceptioncode == 0xc0000094) throw divisionbyzero_exception();
}
int main(int argc, char* argv[])
{
_set_se_translator(translate_seh_exception);
try {
int result = argc / 0;
std::cout << result << std::endl;
}
catch (divisionbyzero_exception& ex) {
std::cout << ex.what() << std::endl;
}
return 0;
}
Do keep in mind that this is completely unportable.
User contributions licensed under CC BY-SA 3.0