C++ does not have a "Division by Zero" Exception to catch. The behavior you're observing is the result of Compiler optimizations:
- The compiler assumes Undefined Behavior doesn't happen
- Division by Zero in C++ is undefined behavior
- Therefore, code which can cause a Division by Zero is presumed to not do so.
- And, code which must cause a Division by Zero is presumed to never happen
- Therefore, the compiler deduces that because Undefined Behavior doesn't happen, then the conditions for Undefined Behavior in this code (
d == 0
) must not happen
- Therefore,
d / d
must always equal 1.
However...
We can force the compiler to trigger a "real" division by zero with a minor tweak to your code.
volatile int d = 0;
d /= d; //What happens?
So now the question remains: now that we've basically forced the compiler to allow this to happen, what happens? It's undefined behavior—but we've now prevented the compiler from optimizing around this undefined behavior.
Mostly, it depends on the target environment. This will not trigger a software exception, but it can (depending on the target CPU) trigger a Hardware Exception (an Integer-Divide-by-Zero), which cannot be caught in the traditional manner a software exception can be caught. This is definitely the case for an x86 CPU, and most other (but not all!) architectures.
There are, however, methods of dealing with the hardware exception (if it occurs) instead of just letting the program crash: look at this post for some methods that might be applicable: Catching exception: divide by zero. Note they vary from compiler to compiler.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…