How to catch a divide by zero error in C++?


The following is an example to catch a divide by zero error.

Example

 Live Demo

#include <iostream>
using namespace std;
int display(int x, int y) {
   if( y == 0 ) {
      throw "Division by zero condition!";
   }
   return (x/y);
}
int main () {
   int a = 50;
   int b = 0;
   int c = 0;
   try {
      c = display(a, b);
      cout << c << endl;
   } catch (const char* msg) {
      cerr << msg << endl;
   }
   return 0;
}

Output

Division by zero condition!

In the above program, a function display() is defined with arguments x and y. It is returning x divide by y and throwing an error.

int display(int x, int y) {
   if( y == 0 ) {
      throw "Division by zero condition!";
   }
   return (x/y);
}

In the main() function, using try catch block, the error is caught by catch block and print the message.

try {
   c = display(a, b);
   cout << c << endl;
} catch (const char* msg) {
   cerr << msg << endl;
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

432 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements