Home >Backend Development >C++ >How Do I Handle Division by Zero Exceptions in C ?

How Do I Handle Division by Zero Exceptions in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-12-29 10:21:10498browse

How Do I Handle Division by Zero Exceptions in C  ?

Catching Exception: Divide by Zero

In C , integer division by zero is not automatically caught as an exception by the runtime. The standard C exceptions do not include an exception specifically for this case.

To handle division by zero, you need to explicitly check for it and throw an exception yourself. This can be done using a condition such as:

if (denominator == 0) {
    throw std::overflow_error("Divide by zero exception");
}

where denominator is the divisor.

Here's an example of how to implement this check:

int main() {
    int i = 42;

    try {
        i = 10 / 0;
    } catch (std::overflow_error &e) {
        std::cout << "Divide by zero exception: " << e.what() << std::endl;
    }

    std::cout << "i after exception: " << i << std::endl;
}

This code will print the following output:

Divide by zero exception: Divide by zero exception
i after exception: 42

By throwing an exception for division by zero, you can handle it gracefully and ensure that your program doesn't crash with an undefined behavior error.

The above is the detailed content of How Do I Handle Division by Zero Exceptions in C ?. 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