How to Handle Divide by Zero Exception in C++
If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial of a number but just think that one user is giving input as -1. It is impossible for the program to calculate the factorial in this case. For this type of case, we need to handle the exception. You may have used if-else conditions to overcome this type of situation. But when you are working professionally, then it will be difficult to read the code if we use the same method because the person who does not have any idea will not understand the actual working code for the extra things which are added for exception handling. C++ language provides us with the advantage of exception handling in some built-in methods. We can use this thing to make our code perfect and understandable at the same time. In this article, we will discuss how to handle divide by zero exception in C++.
Divide By Zero Exception
We all use division in mathematics. In mathematical problems, it often happens that we face some division where we have to divide by zero. When we divide something by zero, the result will be infinite. For this reason, we leave that problem and say that it is a wrong problem. But think that if you have written a code which includes some calculations of division, then it is important to handle the exception of dividing by zero. You can get some idea of this problem from the following code.
Example:
#include <iostream>
using namespace std;
float Division( float a, float b)
{
return (a / b);
}
int main()
{
float a = 14.37;
float b = 0;
float r;
r = Division(a, b);
cout << "The quotient of division is "
<< r << endl;
}
Output:

You can clearly see that the code is giving us the result inf when we divide by zero. But we cannot process this inf in further calculations, so we need to handle exception here.
Exception handling in C++
C++ provides us with the opportunity for exception handling. Exception Handling is one of C++'s benefits over C. Exceptions are irregularities that occur at runtime or other unexpected circumstances that a programme runs into. Two categories of exceptions exist Synchronous and Asynchronous (processes are those that are not under the control of the software, such as disc failure, etc.). For this reason, C++ has the following specific keywords.
- Try: It depicts a section of code with exception-throwing capability.
- Catch: It represents a section of code that runs once a certain exception is thrown.
- Throw: It is employed to raise an error. Exceptions that a function throws but doesn't catch are also listed here.
There are different ways to handle this exception. They are mentioned below:
- Using the runtime_error class: Now, the option of division by zero has been handled, we will look at the exact same code. The main file's try block, which calls the Division function, is present here. In order to determine whether to return the quotient or raise a runtime error exception, the Division function first determines whether the denominator supplied is equal to zero. The catch block intercepts this exception and calls the function with the runtime error object after printing the message "It is exception" and catching the exception. It is used to identify the exception. The what() function is a virtual function of the class Standard exception defined in the stdexcept header file. The software then begins its regular series of instructions after printing the message " Error: It is not possible to divide by zero". Below is the code to implement the above-discussed idea.
Example:
#include <iostream>
#include <stdexcept>
using namespace std;
float Division(float a, float b)
{
if (b == 0) {
throw runtime_error("Error: It is not possible to divide by zero\n");
}
return (a / b);
}
int main()
{
float a, b, r;
a = 14.37;
b = 0;
try {
r = Division(a, b);
cout << "The quotient is "
<< r << endl;
}
catch (runtime_error& e) {
cout << "It is exception" << endl
<< e.what();
}
}
Output:

- Using User defined exception handling: Exception is a class that publicly derives from the runtime error class, which is defined here. We merely define a function constructor for the class Exception, and when it is used, the class object will display the message " Error: It is not possible to divide by zero." We create the division function, which, if the denominator is zero, executes the exception class's function constructor; otherwise, it returns the quotient. We set the numerator and denominator's respective values, 14.37 and 0, inside the main function. The Division function, which will either return the quotient or raise an exception, is then called in the try block. The catch block responds to an exception of type Exception by catching it, displaying the message "It is exception" and then invoking the function. The program picks back up after handling the exception.
Example:
#include <iostream>
#include <stdexcept>
using namespace std;
class Exception : public runtime_error {
public:
Exception()
: runtime_error("Error: It is not possible to divide by zero \n")
{
}
};
float Division(float a, float b)
{
if (b == 0)
throw Exception();
return (a / b);
}
int main()
{
float a, b, r;
a = 14.37;
b = 0;
try {
r = Division(a, b);
cout << "The quotient is " << r << endl;
}
catch (Exception& e) {
cout << " It is exception " << endl
<< e.what();
}
}
Output:

- Using Stack Unwinding: The main function, which is contained within the try block of the stack unwinding, calls the Division function, which in turn calls the CheckDenominator function. The CheckDenominator function determines whether the denominator is 0 and throws an exception if it is; otherwise, it returns the denominator's value. If a non-zero value for the denominator was supplied, the Division function determines the value of the quotient and returns it to the main. Any exception that is raised is caught by the catch block, which also prints the message "It is exception" and invokes the function, which prints " Error: It is not possible to divide by zero “. The show then picks back up.
Example:
#include <iostream>
#include <stdexcept>
using namespace std;
float CheckDenominator(float b)
{
if (b == 0) {
throw runtime_error("Error: It is not possible to divide by zero \n");
}
else
return b;
}
float Division(float a, float b)
{
return (a / CheckDenominator(b));
}
int main()
{
float a, b, r;
a = 14.37;
b = 0;
try {
r = Division(a, b);
cout << "The quotient is "
<< r << endl;
}
catch (runtime_error& e) {
cout << " It is exception " << endl
<< e.what();
}
}
Output:

- Using try and catch(…):The Try block in this code executes the CheckDenominator function. The CheckDenominator function checks to see if the denominator is 0 and, if it is, throws an exception with the string "Error" as a parameter. The catch block recognises this string and prints the message "Exception occured" as a result. Any form of exception can be caught in this catch block.
Example:
#include <iostream>
#include <stdexcept>
using namespace std;
float CheckDenominator(float b)
{
if (b == 0)
throw "Error";
else
return b;
}
int main()
{
float a, b, r;
a = 14.37;
b = 0;
try {
if (CheckDenominator(b)) {
r = (a / b);
cout << "The quotient is "
<< r << endl;
}
}
catch (...) {
cout << " It is exception " << endl;
}
}
Output:

Here we complete all the methods for exception handling in this problem.
Advantages of exception handling over traditional error handling
You must have used if-else statements to handle general errors. Here we have given some points to tell you the advantages of exception handling.
- In traditional error handling codes, there are usually if-else situations to handle issues. These circumstances and the programming to manage errors obstruct the normal flow. The code is hence more challenging to read and maintain. Using try catch blocks, the code for handling failures is segregated from the ordinary flow.
- In C++, exceptions can be thrown for both basic types and objects. Exceptions can be categorized into types, namespaces, or classes, or we can arrange them in a hierarchy.
- Although it may throw more exceptions, a function may choose to handle some of them. Any further exceptions that are thrown but not caught can be handled by the caller. The caller of the caller will handle the exceptions if the caller chooses not to catch them. In C++, a function can declare the exceptions it will throw using the throw keyword. The person using this function must take action to handle the exception.