Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to throw different types of exception & catch them in different catch blocks(Also throw an object )

C++ Code Example — Exception Handling

ADVERTISEMENT

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

  1. Create an empty dummy class Test.
  2. In a function, write multiple if/else conditions.
  3. If a==0 && b==0, throw an integer: throw b;.
  4. If b < 0, throw a string: throw "Message";.
  5. If a < 0, create an object of Test and throw it: Test t; throw t;.
  6. In main(), write three separate catch blocks (for int, const char*, and Test) 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 catch blocks back-to-back. The compiler will automatically check the data type of the thrown exception and route it to the exact catch block that matches that type.

Complexity

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