Catching exception: divide by zero

后端 未结 8 1635
时光取名叫无心
时光取名叫无心 2020-11-22 16:23

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?

8条回答
  •  感情败类
    2020-11-22 17:01

    You 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 by zero but at least that has specific means for dealing with it.

    The exceptions listed in the ISO standard are:

    namespace std {
        class logic_error;
            class domain_error;
            class invalid_argument;
            class length_error;
            class out_of_range;
        class runtime_error;
            class range_error;
            class overflow_error;
            class underflow_error;
    }
    

    and you could argue quite cogently that either overflow_error (the infinity generated by IEEE754 floating point could be considered overflow) or domain_error (it is a problem with the input value) would be ideal for indicating a divide by zero.

    However, section 5.6 (of C++11, though I don't think this has changed from the previous iteration) specifically states:

    If the second operand of / or % is zero, the behavior is undefined.

    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 intDivEx in the following program (using the overflow variant):

    #include 
    #include 
    
    // Integer division, catching divide by zero.
    
    inline int intDivEx (int numerator, int denominator) {
        if (denominator == 0)
            throw std::overflow_error("Divide by zero exception");
        return numerator / denominator;
    }
    
    int main (void) {
        int i = 42;
    
        try { i = intDivEx (10, 2); }
        catch (std::overflow_error e) {
            std::cout << e.what() << " -> ";
        }
        std::cout << i << std::endl;
    
        try { i = intDivEx (10, 0); }
        catch (std::overflow_error e) {
            std::cout << e.what() << " -> ";
        }
        std::cout << i << std::endl;
    
        return 0;
    }
    

    This outputs:

    5
    Divide by zero exception -> 5
    

    and you can see it throws and catches the exception for the divide by zero case.


    The % equivalent is almost exactly the same:

    // Integer remainder, catching divide by zero.
    
    inline int intModEx (int numerator, int denominator) {
        if (denominator == 0)
            throw std::overflow_error("Divide by zero exception");
        return numerator % denominator;
    }
    

提交回复
热议问题