×

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this exception. In general, if we write the code without implementing exception handling then the code gives the output of infinite.

Example 1

#include <iostream>
using namespace std;


float Division(float num, float den)
{
return (num / den);


}


int main()
{
float numerator = 27.6;
float denominator = 0;
float result;
result = Division(numerator, denominator);
cout <<"The quotient of 27.6/0 is "
<< result << endl;
}

Output:

The quotient of 27.6/0 is inf

There are some different ways to handle this situation. Some of the ideas are as follows:

1) Using the runtime_error class

There is a standard library class exception called runtime_error class. This runtime_error class is used to handel the runtime error during presentation of header file exception. Now we are going to try the runtime_error class with the above code and see what we get in the output. There is a try block that called the division function. If the quotient returns zero value then the devison function is being checked by the runtime_error class. The catch block caught that exception and gives the output of which prints the message “Exception occurred”. There is an another function called what() function that is used to defined in stdexcept header file. This function is used to handel the exception.

Example 2

#include <iostream>
#include <stdexcept>
using namespace std;
float Division(float num, float den)
{
if (den == 0) {
throw runtime_error("Math error: Attempted to divide by Zero\n");
}
return (num / den);


}


int main()
{
float numerator, denominator, result;
numerator = 27.6;
denominator = 0;
try {
result = Division(numerator, denominator);
cout <<"The quotient is "
<< result << endl;
}
catch (runtime_error& e) {
cout <<"Exception occurred"<< endl
<< e.what();
}


} 

Output:

Exception occurred
Math error: Attempted to divide by Zero

2) Using User defined exception handling

There is another class function that is used to inherit publically from runtime_error class. In that class, we define a constructor that shows the message “Math error: Attempted to divide by Zero”. When we call the object then this message will appear in the output. Then the catch block catches the exception and shows the message the message “Exception occurred”.

Example 3

#include <iostream>
#include <stdexcept>


using namespace std;


class Exception : public runtime_error {
public:
Exception()
: runtime_error("Math error: Attempted to divide by Zero\n")
{
}
};


float Division(float num, float den)
{
if (den == 0)
throw Exception();
return (num / den);


}


int main()
{
float numerator, denominator, result;
numerator = 27.6;
denominator = 0;
try {
result = Division(numerator, denominator);
cout <<"The quotient is "<< result << endl;
}
catch (Exception& e) {
cout <<"Exception occurred"<< endl
<< e.what();
}


}

Output:

Exception occurred
Math error: Attempted to divide by Zero

Related Topics

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.

Types of polymorphism in C++

What is polymorphism in C++ ? Polymorphism literally translates to "multiple forms". This indicates that the same thing behaves differently depending on the context in programming. Polymorphism is a feature of C++...

6 minutes read.

Passing by Reference Vs. Passing by the pointer in C++

 Passing by Reference Vs. Passing by the pointer in C++ Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have...

3 minutes read.

Bitwise Operator vs Logical Operator

Bitwise Operator  Bitwise operators perform operations bit by bit on bits.The value is converted to abinary during operations like addition, subtraction, division, and so on. These operations are carried out at the...

3 minutes read.

Division in C++

C++ Division Arithmetic Operation In C++ the arithmetic operator / is used for division. This operator takes two operands and returns the result of dividing the left operand by the right...

3 minutes read.

Diamond Pattern using While-loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

5 minutes read.

C++ Close file

C++ File Handling close() Function A file which is opened while reading or writing in file handling must be closed after performing an action on it. The close() function is used to close...

2 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.

C++ if-else

C++ if else Control Statement if else control statement in C++ is used to control the program flow in a two-way direction. When condition returns a true value, then the program executes if condition block otherwise...

1 minute read.

C++ Scope of Variables

In this tutorial, we will explore about the scope of variables in c++ programming language. And also, how it works in a program. What is Scope? The range of applications for something...

4 minutes read.

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.

C++ Continue

In C++, the continue statement is a useful tool for avoiding specific scenarios without breaking the loop. It is employed inside loops to move directly to the following iteration and...

4 minutes read.

C++ vs C#

What exactly is C++ programming? Bjorne Stroustrup is the creator of the C++ programming language. His goal was to create a powerful object-oriented programming language with the capabilities of C. It...

4 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

Programs to Print Pyramid Patterns in C++

We will explore how to use code to print a variety of patterns utilizing stars (*), numbers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,.…)  and alphabets...

7 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.