mike74 said:
For some reason, neither of my catch blocks gets executed. Anyone know how to catch the exception?
divide-by zero is not a “managed” exception. You can still catch it, but it depends on the OS you are using. I'm just assuming you use windows.
There, you would need to use structured-exception handling (which is for system-level exceptions):
__try
{
int a = 0;
int x = 5 / a;
}
__except ((_exception_code() == _STATUS_FLOAT_DIVIDE_BY_ZERO || _exception_code() == _STATUS_INTEGER_DIVIDE_BY_ZERO) ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{
cout << "caught ..." << endl;
}
SEH is much more restricted and low-level than standard exceptions, so you shouldn't use it willy-nilly (and should actually think of another way of handling those errors for the general case). You should probably just check if “a” is 0 and throw your own exception, in the general case.
If you do use SEH, there are two restrictions that you will encounter very early:
- SEH and managed exceptions can't be matched. Meaning, you cannot have both __try and try in the same function. You can solve this by adding a wrapper-function for the other type of exception-handler.
- Locals with destructors (pretty much anything that is non POD) in a function with an SEH-handler are limited. IIRC, you cannot declare a destructable-local before and SEH-handler; or perhaps not at all. You can again solve this by moving the SEH-handler in a wrapper-function.
As you see, most normal usages of SEH are limited. If you haVe to add a wrapper to handle exceptions, you might as well just handle them yourself. SEH is more used for last-ditch error handling (for like a crash-reporter), or where handling all exceptions manually would be tedious (I haVe an own compiler that can execute c++-functions at compile-time; I use SEH to catch any error like div-by-zero during this evaluation gracefully and defer to a compiler-error, without having to sprinkle those functions with manual throws.