Home >Backend Development >C++ >Why Doesn't C Throw an Exception for Integer Divide-by-Zero?

Why Doesn't C Throw an Exception for Integer Divide-by-Zero?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 08:03:14127browse

Why Doesn't C   Throw an Exception for Integer Divide-by-Zero?

Catching Divide-by-Zero Exceptions

Despite attempts to catch an exception using a try/catch block, the following code inexplicably bypasses the exception when dividing by zero:

int i = 0;

cin >> i; // input validation not present

try {
    i = 5/i;
}
catch (std::logic_error e) {

    cerr << e.what();
}

Exception Handling in C

Contrary to expectations, integer division by zero is not a built-in exception in standard C . This is also true for floating-point division/remainder by zero, although in this case, specific rational values like NaN/Inf may result.

The list of exceptions defined in the ISO C 20 standard includes:

logic_error
domain_error
invalid_argument
length_error
out_of_range
runtime_error
range_error
overflow_error
underflow_error

While arguments could be made for using overflow_error or domain_error to indicate a divide-by-zero, the standard explicitly states that the behavior is undefined in such cases.

Custom Exception Handling

If a divide-by-zero exception is desired, it can be implemented manually. The following example uses the intDivEx function to divide integers with exception handling:

inline int intDivEx (int numerator, int denominator) {
    if (denominator == 0)
        throw std::overflow_error("Divide by zero exception");
    return numerator / denominator;
}

The output of using this function demonstrates the exception being thrown and caught, leaving the original variable untouched in the case of a divide-by-zero:

i = intDivEx(10, 0); // throws exception

i = intDivEx(10, 2); // returns 5

The above is the detailed content of Why Doesn't C Throw an Exception for Integer Divide-by-Zero?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn