Handling the Divide by Zero Exception in C++


In this tutorial, we will be discussing how to handle the divide by Zero exception in C++.

Division by zero is an undefined entity in mathematics, and we need to handle it properly while programming so that it doesn’t return at error at the user end.

Using the runtime_error class

Example

 Live Demo

#include <iostream>
#include <stdexcept>
using namespace std;
//handling divide by zero
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

Using user defined exception handling

Example

 Live Demo

#include <iostream>
#include <stdexcept>
using namespace std;
//user defined class for handling exception
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;
   //trying block calls the Division function
   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

Using stack unwinding

Example

 Live Demo

#include <iostream>
#include <stdexcept>
using namespace std;
//defining function to handle exception
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

Updated on: 17-Feb-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements