WAP to throw different types of exception & catch them in different catch blocks(Also throw an object )
Objective
Write a C++ program to throw different types of exceptions and catch them in different catch blocks.
Algorithm / Approach
- Create an empty dummy
class Test. - In a function, write multiple
if/elseconditions. - If
a==0 && b==0, throw an integer:throw b;. - If
b < 0, throw a string:throw "Message";. - If
a < 0, create an object of Test and throw it:Test t; throw t;. - In
main(), write three separatecatchblocks (forint,const char*, andTest) to catch whichever specific exception gets thrown.
main.cpp
#include<iostream>
using namespace std;
class Test {
public :
void show() {
cout<<"Wrong input ";
}
};
class Demo {
public :
void disp(int a, int b) {
if(b==0 && a==0) {
throw b;
}
else if(b < 0) {
throw "2nd variable must be +ve ";
}
else if(a < 0) {
Test t;
throw t;
}
else {
cout<<"Fair = "<< a<<"."<< b;
}
}
};
int main() {
Demo d;
int x,y;
cout<<"Enter Fair ";
cin>>x>>y;
try {
d.disp(x,y);
}
catch(int i) {
cout<<"Fair can't be = " << i;
}
catch(const char *a) {
cout<< a;
}
catch(Test t) {
t.show();
}
return 0;
}
Expected Output
Enter Fair 0 0 Fair can't be = 0
Explanation of the Program
- C++ allows you to throw ANY data type as an exception: primitives like integers and strings, or complex custom class objects.
- You can string multiple
catchblocks back-to-back. The compiler will automatically check the data type of the thrown exception and route it to the exactcatchblock that matches that type.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)