Catch exception divide by zero


I need to catch the exception divided by zero in C ++. I was reading that exceptions like this one are not defined in C ++; I saw some examples but they use signal() , in others they use the throw() and the truth is that it confused me a lot.

asked by Franco Cortes 01.07.2018 в 05:27

1 answer


I need to catch the divide by zero exception in C ++.

Bad news, that exception does not exist. As indicated by the C ++ standard (translation and highlighting mine) :


5.4 Expressions


If during the evaluation of an expression, the result is not mathematically defined or it is not in the range that can be represented by the values of its type, the behavior is undefined . [ Note: Many of the existing C ++ implementations ignore integer overflow. The division treatment between zero , calculate the remainder on a zero divisor and all floating point exceptions vary between machines , and is usually adjustable by a library function - end of the note ]

The division between zero is, by definition, a mathematical indetermination and (as stated in the standard) causes undefined behavior and does not throw any exception; so you will not be able to catch her.

What you can do is throw the exception on your own and catch it:

template <typename DIVIDENDO, typename DIVISOR>
auto divide(DIVIDENDO a, DIVISOR b)
    return b == 0 ? throw std::logic_error("divide by zero") : a / b;

int main()
        std::cout << divide(1, 0) << '\n';
    catch (const std::logic_error &le)
        // hacer cosas
    return 0;
answered by 02.07.2018 в 08:53