Demonstrate try, catch block - C++ Program

Q. Write a C++ program to demonstrate the use of try, catch block with the argument as an integer and string using multiple catch blocks.

Answer:

  • Exception handling means handling of abnormal or unexpected events.
  • Exception handling is done by 'try', 'catch', 'throw' keywords.
  • It transfers the control to special functions called Handlers and makes it easy to separate the error handling code.
Following program is demonstrating the use of try, catch block with the argument as an integer and string using multiple catch blocks.

#include<iostream>
using namespace std;
void test_try(int num)
{
        try
        {
                if(num>=0 && num<=9)
                        throw num;
                else
                        cout<<"\n It is not a Single Number ";
                throw;
        }
        catch(int a)
        {
                cout<<"\n It is a Single Number";
        }
        catch(char b[100])
        {
                cout<<b;
        }
}
int main()
{
        int num;
        cout<<"\n Enter Number : ";
        cin>>num;
        test_try(num);
        return 0;
}


Output:

try multiple catch

try multiple catch