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
Release: 2024-12-29 10:21:10
Original
507 people have browsed it

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");
}
Copy after login

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;
}
Copy after login

This code will print the following output:

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

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template