Open In App

Handling the Divide by Zero Exception in C++

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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

  • 1) Using the runtime_error class

    The runtime_error class is a derived class of Standard Library class exception, defined in exception header file for representing runtime errors.
    Now we consider the exact same code but included with handling the division by zero possibility. Here, we have the try block inside main that calls the Division function. The Division function checks if the denominator passed is equal to zero if no it returns the quotient, if yes it throws a runtime_error exception. This Exception is caught by the catch block which prints the message “Exception occurred” and then calls the what function with runtime_error object e. The what() function {used in the code given below} is a virtual function of the class Standard exception defined in stdexcept header file, it is used to identify the exception. This prints the message “Math error: Attempted to divide by Zero”, after which the program resumes the ordinary sequence of instructions.




    // Program to depict how to handle
    // divide by zero exception
      
    #include <iostream>
    #include <stdexcept> // To use runtime_error
    using namespace std;
      
    // Defining function Division
    float Division(float num, float den)
    {
        // If denominator is Zero
        // throw runtime_error
        if (den == 0) {
            throw runtime_error("Math error: Attempted to divide by Zero\n");
        }
      
        // Otherwise return the result of division
        return (num / den);
      
    } // end Division
      
    int main()
    {
        float numerator, denominator, result;
        numerator = 12.5;
        denominator = 0;
      
        // try block calls the Division function
        try {
            result = Division(numerator, denominator);
      
            // this will not print in this example
            cout << "The quotient is "
                 << result << endl;
        }
      
        // catch block catches exception thrown
        // by the Division function
        catch (runtime_error& e) {
      
            // prints that exception has occurred
            // calls the what function
            // using runtime_error object
            cout << "Exception occurred" << endl
                 << e.what();
        }
      
    } // end main

    
    

    Output:

    Exception occurred
    Math error: Attempted to divide by Zero
    
  • 2) Using User defined exception handling

    Here we define a class Exception that publicly inherits from runtime_error class. Inside the class Exception, we define only a constructor that will display the message “Math error: Attempted to divide by Zero” when called using the class object. We define the Division function that calls the constructor of class Exception when denominator is zero otherwise returns the quotient. Inside of main we give some values to numerator and denominator, 12.5 and 0 respectively. Then we come to the try block that calls the Division function which will either return the quotient or throw an exception. The catch block catches the exception of type Exception, displays the message “Exception occurred” and then calls the what function. After the exception is handled the program resumes.




    // Program to depict user defined exception handling
      
    #include <iostream>
    #include <stdexcept>
    // For using runtime_error
      
    using namespace std;
      
    // User defined class for handling exception
    // Class Exception publicly inherits
    // the runtime_error class
      
    class Exception : public runtime_error {
    public:
        // Defining constructor of class Exception
        // that passes a string message to the runtime_error class
        Exception()
            : runtime_error("Math error: Attempted to divide by Zero\n")
        {
        }
    };
      
    // defining Division function
    float Division(float num, float den)
    {
      
        // If denominator is Zero
        // throw user defined exception of type Exception
        if (den == 0)
            throw Exception();
      
        // otherwise return the result of division
        return (num / den);
      
    } // end Division
      
    int main()
    {
        float numerator, denominator, result;
        numerator = 12.5;
        denominator = 0;
      
        // try block calls the Division function
        try {
            result = Division(numerator, denominator);
      
            // this will not print in this example
            cout << "The quotient is " << result << endl;
        }
      
        // catch block catches exception if any
        // of type Exception
        catch (Exception& e) {
      
            // prints that exception has occurred
            // calls the what function using object of
            // the user defined class called Exception
            cout << "Exception occurred" << endl
                 << e.what();
        }
      
    } // end main

    
    

    Output:

    Exception occurred
    Math error: Attempted to divide by Zero
    
  • 3) Using Stack Unwinding

    In stack unwinding we have the main inside which the try block calls the Division function which in turn calls the CheckDenominator function. The CheckDenominator function checks if denominator is zero, if true throws an exception otherwise returns the value of denominator. The Division function calculates the value of quotient {if non-zero value of denominator was passed} and returns the same to the main. The catch block catches any exception thrown and displays the message “Exception occurred” and calls the what function which prints “Math error: Attempted to divide by zero”. After this the program resumes.




    // Program to depict Exception Handling
    // Using stack unwinding
      
    #include <iostream>
    #include <stdexcept>
    using namespace std;
      
    // defining the CheckDenominator function
    float CheckDenominator(float den)
    {
      
        // if denominator is zero
        // throw exception
        if (den == 0) {
            throw runtime_error("Math error: Attempted to divide by zero\n");
        }
        else
            return den;
    } // end CheckDenominator
      
    // defining Division function
    float Division(float num, float den)
    {
        // Division function calls CheckDenominator
        return (num / CheckDenominator(den));
      
    } // end Division
      
    int main()
    {
        float numerator, denominator, result;
        numerator = 12.5;
        denominator = 0;
      
        // try block calls the Division function
        try {
            result = Division(numerator, denominator);
      
            // This will not print in this example
            cout << "The quotient is "
                 << result << endl;
        }
      
        // catch block catches exception if any
        catch (runtime_error& e) {
      
            // prints that exception has occurred
            // calls the what function using object of
            // runtime_error class
            cout << "Exception occurred" << endl
                 << e.what();
        }
    } // end main

    
    

    Output:

    Exception occurred
    Math error: Attempted to divide by zero
    
  • 4) Using try and catch(…)

    In this code the try block calls the CheckDenominator function. In CheckDenominator function we check if denominator is zero, if true throw an exception by passing a string “Error”. This string is caught by the catch block and therefore prints the message “Exception occurred”. The catch block here is capable of catching exception of any type.




    // Program to depict use of try catch block
      
    #include <iostream>
    #include <stdexcept>
    using namespace std;
      
    // defining CheckDenominator
    float CheckDenominator(float den)
    {
        if (den == 0)
            throw "Error";
        else
            return den;
    } // end CheckDenominator
      
    int main()
    {
        float numerator, denominator, result;
        numerator = 12.5;
        denominator = 0;
      
        // try block
        try {
      
            // calls the CheckDenominator function
            // by passing a string "Error"
            if (CheckDenominator(denominator)) {
      
                result = (numerator / denominator);
                cout << "The quotient is "
                     << result << endl;
            }
        }
      
        // catch block
        // capable of catching any type of exception
        catch (...) {
      
            // Display a that exception has occurred
            cout << "Exception occurred" << endl;
        }
      
    } // end main

    
    

    Output:

    Exception occurred
    


Last Updated : 23 Jan, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads