The following code does not catch an exception, when I try to divide by 0. Do I need to throw an exception, or does the computer automatically throw one at runtime?
int i = 0;
cin >> i; // what if someone enters zero?
try {
i = 5/i;
}
catch (std::logic_error e) {
cerr << e.what();
}
You will need to check it yourself and throw an exception. Integer divide by zero is not an exception in standard C++. Neither is floating point divide/remainder by zero but at least that has specific rational values that may result (such as the various
NaN/Infvalues).The exceptions listed in the
[stdexcept.syn]section ofISO C++20standard (the iteration used in this answer) are:Now you could argue quite cogently that either
overflow_error(the infinity generated by IEEE754 floating point could be considered overflow) ordomain_error(it is, after all, a problem with the input value) would be ideal for indicating a divide by zero.However, section
[expr.mul]specifically states (for both integer and floating point division, and integer remainder):So, it could throw those (or any other) exceptions. It could also format your hard disk and laugh derisively 🙂
If you wanted to implement such a beast, you could use something like
intDivExin the following program (using the overflow variant):This outputs:
You can see it throws and catches the exception (leaving the return variable untouched) for the divide by zero case.