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 |
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_errorusingnamespacestd;// Defining function DivisionfloatDivision(floatnum,floatden){// If denominator is Zero// throw runtime_errorif(den == 0) {throwruntime_error("Math error: Attempted to divide by Zero\n");}// Otherwise return the result of divisionreturn(num / den);}// end Divisionintmain(){floatnumerator, denominator, result;numerator = 12.5;denominator = 0;// try block calls the Division functiontry{result = Division(numerator, denominator);// this will not print in this examplecout <<"The quotient is "<< result << endl;}// catch block catches exception thrown// by the Division functioncatch(runtime_error& e) {// prints that exception has occurred// calls the what function// using runtime_error objectcout <<"Exception occurred"<< endl<< e.what();}}// end mainchevron_rightfilter_noneOutput: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_errorusingnamespacestd;// User defined class for handling exception// Class Exception publicly inherits// the runtime_error classclassException :publicruntime_error {public:// Defining constructor of class Exception// that passes a string message to the runtime_error classException(): runtime_error("Math error: Attempted to divide by Zero\n"){}};// defining Division functionfloatDivision(floatnum,floatden){// If denominator is Zero// throw user defined exception of type Exceptionif(den == 0)throwException();// otherwise return the result of divisionreturn(num / den);}// end Divisionintmain(){floatnumerator, denominator, result;numerator = 12.5;denominator = 0;// try block calls the Division functiontry{result = Division(numerator, denominator);// this will not print in this examplecout <<"The quotient is "<< result << endl;}// catch block catches exception if any// of type Exceptioncatch(Exception& e) {// prints that exception has occurred// calls the what function using object of// the user defined class called Exceptioncout <<"Exception occurred"<< endl<< e.what();}}// end mainchevron_rightfilter_noneOutput: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>usingnamespacestd;// defining the CheckDenominator functionfloatCheckDenominator(floatden){// if denominator is zero// throw exceptionif(den == 0) {throwruntime_error("Math error: Attempted to divide by zero\n");}elsereturnden;}// end CheckDenominator// defining Division functionfloatDivision(floatnum,floatden){// Division function calls CheckDenominatorreturn(num / CheckDenominator(den));}// end Divisionintmain(){floatnumerator, denominator, result;numerator = 12.5;denominator = 0;// try block calls the Division functiontry{result = Division(numerator, denominator);// This will not print in this examplecout <<"The quotient is "<< result << endl;}// catch block catches exception if anycatch(runtime_error& e) {// prints that exception has occurred// calls the what function using object of// runtime_error classcout <<"Exception occurred"<< endl<< e.what();}}// end mainchevron_rightfilter_noneOutput: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>usingnamespacestd;// defining CheckDenominatorfloatCheckDenominator(floatden){if(den == 0)throw"Error";elsereturnden;}// end CheckDenominatorintmain(){floatnumerator, denominator, result;numerator = 12.5;denominator = 0;// try blocktry{// 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 exceptioncatch(...) {// Display a that exception has occurredcout <<"Exception occurred"<< endl;}}// end mainchevron_rightfilter_noneOutput:Exception occurred
Recommended Posts:
- Comparison of Exception Handling in C++ and Java
- Exception Handling in C++
- Customizing termination behavior for uncaught exception In C++
- User-defined Custom Exception with class in C++
- Exception header in C++ with examples
- Divide the two given numbers by their common divisors
- Divide two integers without using multiplication, division and mod operator | Set2
- Generate a random permutation of elements from range [L, R] (Divide and Conquer)
- Custom Jumble Word Game
- Comparator Class in C++ with Examples
- Competitive Coding Setup for C++ and Python in VS Code using Python Script
- Program to find largest element in an array using Dynamic Memory Allocation
- Life cycle of Objects in C++ with Example
- Minimum N-Digit number required to obtain largest N-digit number after performing given operations
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

