×

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

Naming Convention in C++

The first and most fundamental step a programmer takes to produce clean code is to name a file or a variable. This naming must be acceptable so that it serves...

5 minutes read.

This keyword in C++

This keyword in C++ is a pointer which points to the object. It is passed as an argument to functions which helps in accessing the object. It is used for a...

3 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

C++ Program For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 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.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

Program to find the GCD of two numbers in C++

Before understanding the program of GCD or HCF, one must know what GCD or HCF is. What is GCD? The GCD is referred to as Greatest Common Divisor. HCF is the other...

8 minutes read.

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

Dynamic _Cast in C++

C++ is one of the most powerful programming languages. We can write object-oriented and structured programming with the help of C++. In this article, we will learn about the dynamic...

3 minutes read.

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 minutes read.

Binary to Decimal in C++

We must create a software to convert a binary number into an equivalent decimal value given a binary number as input. Example: // C++ program to convert binary to decimal #include < iostream...

3 minutes read.

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.

C++ Ternary Operator

In this tutorial, we'll learn about the C++ ternary operator and how to utilise it to manage the program's flow using examples. Ternary Operator: The if-else statement and the conditional operator use...

3 minutes read.

Call by Pointer in C++

What is Pointer? Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined...

5 minutes read.

Armstrong Number 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...

4 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.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.