×

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial of a number but just think that one user is giving input as -1. It is impossible for the program to calculate the factorial in this case. For this type of case, we need to handle the exception. You may have used if-else conditions to overcome this type of situation. But when you are working professionally, then it will be difficult to read the code if we use the same method because the person who does not have any idea will not understand the actual working code for the extra things which are added for exception handling. C++ language provides us with the advantage of exception handling in some built-in methods. We can use this thing to make our code perfect and understandable at the same time. In this article, we will discuss how to handle divide by zero exception in C++.

Divide By Zero Exception

We all use division in mathematics. In mathematical problems, it often happens that we face some division where we have to divide by zero. When we divide something by zero, the result will be infinite. For this reason, we leave that problem and say that it is a wrong problem. But think that if you have written a code which includes some calculations of division, then it is important to handle the exception of dividing by zero. You can get some idea of this problem from the following code.

Example:

#include <iostream>
using namespace std;
float Division( float a, float b)
{
	return (a / b);


} 


int main()
{
	float a = 14.37;
	float b = 0;
	float r;
	r = Division(a, b);
	cout << "The quotient of division is "
		<< r << endl;
} 

Output:

How to Handle Divide by Zero Exception in C++

You can clearly see that the code is giving us the result inf when we divide by zero. But we cannot process this inf in further calculations, so we need to handle exception here.

Exception handling in C++

C++ provides us with the opportunity for exception handling. Exception Handling is one of C++'s benefits over C. Exceptions are irregularities that occur at runtime or other unexpected circumstances that a programme runs into. Two categories of exceptions exist Synchronous and Asynchronous (processes are those that are not under the control of the software, such as disc failure, etc.). For this reason, C++ has the following specific keywords.

  1. Try: It depicts a section of code with exception-throwing capability.
  2. Catch: It represents a section of code that runs once a certain exception is thrown.
  3. Throw: It is employed to raise an error. Exceptions that a function throws but doesn't catch are also listed here.

There are different ways to handle this exception. They are mentioned below:

  • Using the runtime_error class: Now, the option of division by zero has been handled, we will look at the exact same code. The main file's try block, which calls the Division function, is present here. In order to determine whether to return the quotient or raise a runtime error exception, the Division function first determines whether the denominator supplied is equal to zero. The catch block intercepts this exception and calls the function with the runtime error object after printing the message "It is exception" and catching the exception. It is used to identify the exception. The what() function is a virtual function of the class Standard exception defined in the stdexcept header file. The software then begins its regular series of instructions after printing the message " Error: It is not possible to divide by zero". Below is the code to implement the above-discussed idea.

Example:

#include <iostream>
#include <stdexcept> 
using namespace std;
float Division(float a, float b)
{
	if (b == 0) {
		throw runtime_error("Error: It is not possible to divide by zero\n");
	}
	return (a / b);


} 


int main()
{
	float a, b, r;
	a = 14.37;
	b = 0;
	try {
		r = Division(a, b);
		cout << "The quotient is "
			<< r << endl;
	}
	catch (runtime_error& e) {
		cout << "It is exception" << endl
			<< e.what();
	}


} 

Output:

How to Handle Divide by Zero Exception in C++
  • Using User defined exception handling: Exception is a class that publicly derives from the runtime error class, which is defined here. We merely define a function constructor for the class Exception, and when it is used, the class object will display the message " Error: It is not possible to divide by zero." We create the division function, which, if the denominator is zero, executes the exception class's function constructor; otherwise, it returns the quotient. We set the numerator and denominator's respective values, 14.37 and 0, inside the main function. The Division function, which will either return the quotient or raise an exception, is then called in the try block. The catch block responds to an exception of type Exception by catching it, displaying the message "It is exception" and then invoking the function. The program picks back up after handling the exception.

Example:

#include <iostream>
#include <stdexcept>


using namespace std;


class Exception : public runtime_error {
public:
	Exception()
		: runtime_error("Error: It is not possible to divide by zero \n")
	{
	}
};
float Division(float a, float b)
{
	if (b == 0)
		throw Exception();
	return (a / b);


} 


int main()
{
	float a, b, r;
	a = 14.37;
	b = 0;
	try {
		r = Division(a, b);
		cout << "The quotient is " << r << endl;
	}
	catch (Exception& e) {
		cout << " It is exception " << endl
			<< e.what();
	}


}

Output:

How to Handle Divide by Zero Exception in C++
  •  Using Stack Unwinding: The main function, which is contained within the try block of the stack unwinding, calls the Division function, which in turn calls the CheckDenominator function. The CheckDenominator function determines whether the denominator is 0 and throws an exception if it is; otherwise, it returns the denominator's value. If a non-zero value for the denominator was supplied, the Division function determines the value of the quotient and returns it to the main. Any exception that is raised is caught by the catch block, which also prints the message "It is exception" and invokes the function, which prints " Error: It is not possible to divide by zero “. The show then picks back up.

Example:

#include <iostream>
#include <stdexcept>
using namespace std;
float CheckDenominator(float b)
{
	if (b == 0) {
		throw runtime_error("Error: It is not possible to divide by zero \n");
	}
	else
		return b;
} 
float Division(float a, float b)
{
	return (a / CheckDenominator(b));


} 


int main()
{
	float a, b, r;
	a = 14.37;
	b = 0;
	try {
		r = Division(a, b);
		cout << "The quotient is "
			<< r << endl;
	}
	catch (runtime_error& e) {
		cout << " It is exception " << endl
			<< e.what();
	}
} 

Output:

How to Handle Divide by Zero Exception in C++
  •  Using try and catch(…):The Try block in this code executes the CheckDenominator function. The CheckDenominator function checks to see if the denominator is 0 and, if it is, throws an exception with the string "Error" as a parameter. The catch block recognises this string and prints the message "Exception occured" as a result. Any form of exception can be caught in this catch block.

Example:

#include <iostream>
#include <stdexcept>
using namespace std;
float CheckDenominator(float b)
{
	if (b == 0)
		throw "Error";
	else
		return b;
} 
int main()
{
	float a, b, r;
	a = 14.37;
	b = 0;
	try {
		if (CheckDenominator(b)) {


			r = (a / b);
			cout << "The quotient is "
				<< r << endl;
		}
	}
	catch (...) {
		cout << " It is exception " << endl;
	}


} 


Output:

How to Handle Divide by Zero Exception in C++

Here we complete all the methods for exception handling in this problem.

Advantages of exception handling over traditional error handling

You must have used if-else statements to handle general errors. Here we have given some points to tell you the advantages of exception handling.

  • In traditional error handling codes, there are usually if-else situations to handle issues. These circumstances and the programming to manage errors obstruct the normal flow. The code is hence more challenging to read and maintain. Using try catch blocks, the code for handling failures is segregated from the ordinary flow.
  • In C++, exceptions can be thrown for both basic types and objects. Exceptions can be categorized into types, namespaces, or classes, or we can arrange them in a hierarchy.
  • Although it may throw more exceptions, a function may choose to handle some of them. Any further exceptions that are thrown but not caught can be handled by the caller. The caller of the caller will handle the exceptions if the caller chooses not to catch them. In C++, a function can declare the exceptions it will throw using the throw keyword. The person using this function must take action to handle the exception.

Related Topics

Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a...

2 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

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

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.

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.

Backtracking Time Complexity in C++

Introduction to Backtracking Backtracking is an important part of programming languages, and with the help of backtracking, we can do many operations in an advanced data structure. For doing major operations,...

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

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

C++ | C Plus Plus Data type

Data type in every language is very important. Data type means the different kinds of data that are supported by a particular programming language. A computer language’s data types specify the...

15 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

How to call a void function in C++

Generally, any function has two types: 1. Void function: It doesn't return any value. 2. Non-void function: It returns some value. Program to call a void function in C++ #include <iostream> using namespace std;  void check() {  ...

2 minutes read.

C++ program to read string using cin.getline()

C++ program to read string using cin.getline() C++ getline() is a standard library feature for reading a string or a line from an input source. A getline() function gets characters from...

3 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

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

2 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

C++ Try-Catch

Every useful program will eventually encounter unexpected outcomes. By entering data that are incorrect, users might create mistakes. Sometimes the program's creator didn't consider all of the options or was...

7 minutes read.

10 Best C and C++ Books for Beginners & Advanced Programmers

If you want to become a skilled software developer, you should never stop learning, whether you're a working professional or a student. Why, therefore, only C or C++? The fundamental...

6 minutes read.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.