How do you handle an "arithmetic exception," like division by zero, in C++?
How do you handle an "arithmetic exception," like division by zero, in C++?
680
16-Aug-2023
Updated on 17-Aug-2023
Aryan Kumar
17-Aug-2023To handle an arithmetic exception like division by zero in C++, you can use the following steps:
tryblock contains the code that you are trying to execute. If an error occurs, thecatchblock will be executed.ArithmeticExceptionexception. TheArithmeticExceptionexception is thrown when an arithmetic error occurs, such as division by zero.Here is an example of how to handle an arithmetic exception in C++:
C++
In this example, the
tryblock contains the code that attempts to dividenum1bynum2. If the division is successful, thecatchblock will not be executed. However, if the division fails becausenum2is zero, theArithmeticExceptionexception will be thrown and thecatchblock will be executed. In thecatchblock, we simply print a message to the user indicating that a division by zero error has occurred.It is important to note that not all arithmetic errors are thrown as
ArithmeticExceptionexceptions. For example, overflow errors are not thrown asArithmeticExceptionexceptions. If you need to handle all arithmetic errors, you can use thestd::runtime_errorexception.