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.
#include <iostream>
using namespace std;
float Division( float num, float den)
{
return (num / den);
}
int main()
{
float numerator = 12.5;
float denominator = 0;
float result;
result = Division(numerator, denominator);
cout << "The quotient of 12.5/0 is "
<< result << endl;
}
|
Output:
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.
#include <iostream>
#include <stdexcept> // To use runtime_error
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 = 12.5;
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
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.
#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 = 12.5;
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
- 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.
#include <iostream>
#include <stdexcept>
using namespace std;
float CheckDenominator( float den)
{
if (den == 0) {
throw runtime_error( "Math error: Attempted to divide by zero\n" );
}
else
return den;
}
float Division( float num, float den)
{
return (num / CheckDenominator(den));
}
int main()
{
float numerator, denominator, result;
numerator = 12.5;
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
- 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.
#include <iostream>
#include <stdexcept>
using namespace std;
float CheckDenominator( float den)
{
if (den == 0)
throw "Error" ;
else
return den;
}
int main()
{
float numerator, denominator, result;
numerator = 12.5;
denominator = 0;
try {
if (CheckDenominator(denominator)) {
result = (numerator / denominator);
cout << "The quotient is "
<< result << endl;
}
}
catch (...) {
cout << "Exception occurred" << endl;
}
}
|
Output:
Exception occurred
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
23 Jan, 2019
Like Article
Save Article