Home >Backend Development >C++ >How to Gracefully Handle Divide-by-Zero Exceptions in C ?

How to Gracefully Handle Divide-by-Zero Exceptions in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-04 02:54:42776browse

How to Gracefully Handle Divide-by-Zero Exceptions in C  ?

Handling Divide by Zero Exception

Integers in C lack native exception support. So, in the code snippet provided:

int i = 0;

cin >> i;  // Input might be zero

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

    cerr << e.what();
}

when the input is zero, it will result in undefined behavior rather than triggering an exception. To handle such scenarios, you need to perform the check and throw an exception explicitly.

In the following code, we handle division by zero exceptions using the intDivEx method:

#include <iostream>
#include <stdexcept>

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

int main() {
    int i = 42;

    try {
        i = intDivEx(10, 0);
    } catch (std::overflow_error &e) {
        std::cout << e.what() << " -> ";
    }
    std::cout << i << std::endl;

    try {
        i = intDivEx(10, 2);
    } catch (std::overflow_error &e) {
        std::cout << e.what() << " -> ";
    }
    std::cout << i << std::endl;

    return 0;
}

This code checks for division by zero before performing the operation. If an exception occurs, it prints an error message. Otherwise, it continues the execution.

The above is the detailed content of How to Gracefully Handle Divide-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