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()
{
try
{
std::cout << divide(1, 0) << '\n';
}
catch (const std::logic_error &le)
{
// hacer cosas
}
return 0;
}