Handling Divide by Zero Exception in C++

Hello Learners, Today in this tutorial we will learn How to handle divide by zero exceptions in C++ with some easy and comprehensible examples. There are two types of statements in the program Normal statements and the other is Critical statements. Let’s discuss this in more detail.

Normal Statements:

 int i = 5;

Critical Statements:

 int k = i/j;
Here 'j' might be equal to zero the 'k' will be not defined.

Always write critical statements using try and catch block.

So, this is an exception that if ‘j’ will be zero, we can use exception handling (try and catch block)to overcome the exceptions that occur when we execute the program.

Note: Exceptions can be handled but Error can’t be handled.

We can handle divide by zero exception using try and catch block.

Here is the code.

#include <iostream>
using namespace std;

int main()
{
    float i, j;

    cout << "Enter numerator: " << endl;
    std::cin >> i;
    cout << "Enter denominator:" << endl;
    std::cin >> j;

    try{

        if(j == 0)
        throw "Error";

        float k = i/j;
        cout  << i<< "/" << j << " = "<< k;
    }

    // (...) can handle any type of exception 
    // or default 

    catch(...)
    {
        cout<< "Trying to divide by zero\n";
    }
}

Output:

Enter numerator:10
Enter denominator:5
10/5 = 2
Enter numerator:12
Enter denominator:0
Trying to divide by zero

I hope this article was helpful to you. Keep Coding Keep Learning.