Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to handle divide by zero Exception

C++ Code Example — Exception Handling

ADVERTISEMENT

WAP to handle divide by zero Exception

Objective

Write a C++ program to handle a Divide by Zero Exception.

Algorithm / Approach

  1. Create a class Test with a function add(int a, int b).
  2. Inside the function, check if the denominator b == 0.
  3. If true, use the throw keyword to throw a string message ("Can't Divide by Zero").
  4. In main(), wrap the function call inside a try block.
  5. Use a catch (const char *a) block to catch the string exception and print it.
main.cpp
#include<iostream>
using namespace std ;
class Test {
 public :
 void add(int a , int b) {
  if(b==0) {
   throw "Can't Divide by Zero ";
  }
  else {
   int c= a/b;
  cout<< c<< endl;
  }
 }
};
int main() {
 Test t;
 int x,y;
 cout<<"Enter two number ";
 cin>>x>>y;
 try { 
    t.add(x,y);
  }
 catch(const char *a) {
  cout<< a<< endl;
  }
return 0;
}

Expected Output

Enter two number 5 0
Can't Divide by Zero

Explanation of the Program

  • Exception Handling is a mechanism to handle runtime errors gracefully, preventing the entire program from instantly crashing.
  • When b == 0, the program explicitly throws an exception. Execution immediately jumps out of the try block and looks for a matching catch block to handle the error.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT