Divide by zero in C++

Why doesn't a divide-by-zero cause an exception in C++?

It was a specific design decision of C++ not to handle divide-by-zero; whereas Java and Ada, for example, take the opposite view. Why? The usual answers -- efficiency and an assumption that C++ will tend to be used with more of an awareness of the hardware.

Stroustrup says, in "The Design and Evolution of C++" (Addison Wesley, 1994), "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."

So you must check your divisors yourself, or discover if your hardware maps divide-by-zero onto some other kind of exception and catch that. It's fairly easy to discover the latter. Just put a try {} catch (...) {} around a divide by zero.

[ Briefings Home Page | Training Courses from John Deacon | Books by John Deacon | JDL Home Page ]

Last modified: Friday February 08, 2002.
Copyright © 2002 John Deacon. All rights reserved.
Questions or problems regarding this web site should be directed to me  jdeacon27@gmail.com.