WAP to handle divide by zero Exception
Objective
Write a C++ program to handle a Divide by Zero Exception.
Algorithm / Approach
- Create a
class Testwith a functionadd(int a, int b). - Inside the function, check if the denominator
b == 0. - If true, use the
throwkeyword to throw a string message ("Can't Divide by Zero"). - In
main(), wrap the function call inside atryblock. - 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 thetryblock and looks for a matchingcatchblock to handle the error.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)