Open In App

Handling the Divide by Zero Exception in C++

We use Exception Handling to overcome exceptions occurred in execution of a program in a systematic manner.

Dividing a number by Zero is a mathematical error (not defined) and we can use exception handling to gracefully overcome such operations. If you write a code without using exception handling then the output of division by zero will be shown as infinity which cannot be further processed.



Consider the code given below, the Division function returns the result of numerator divided by denominator which is stored in the variable result in the main and then displayed. This Division function does not have any rumination for denominator being zero.




// Program to show division without using
// Exception Handling
  
#include <iostream>
using namespace std;
  
// Defining function Division
float Division(float num, float den)
{
    // return the result of division
    return (num / den);
  
} // end Division
  
int main()
{
    // storing 12.5 in numerator
    // and 0 in denominator
    float numerator = 12.5;
    float denominator = 0;
    float result;
  
    // calls Division function
    result = Division(numerator, denominator);
  
    // display the value stored in result
    cout << "The quotient of 12.5/0 is "
         << result << endl;
  
} // end main

Output:
The quotient of 12.5/0 is inf

We can handle this exception in a number of different ways, some of which are listed below




Article Tags :