Demonstrate try, throw and catch statement

Q. Write a C++ program to demonstrate try, throw and catch statement.

Answer:

#include<iostream>
using namespace std;

int main ()
{
     try
     {
          throw 'e';
     }
     catch (char e)
     {
          cout << "\n Exception Caught '"<<e<<"'"<<endl;
     }
     return 0;
}


Output:

simple try catch block

Explanation:
  • In the above example, it throws an exception that is throw 'e'.
  • A throw exception accepts one parameter (in this case character 'e'), which is passed as an argument to the exception handler.
  • Exception handler is declared with the catch keyword. It is mandatory to write catch block after the try block.
  • Catch block is similar to regular function which always has at least one parameter and the type of the parameter is very important because, the type of the parameter/argument passed by the throw exception is checked against it, and only in the case they match, the exception is caught.
  • Throw statement is executed when the handler matches its type with the argument which is specified in the statement.