Exception Handling in C++

Exception handling in C++ programming consist of three keywords try, throw, and catch. Exception handling provides a way to transfer control from one part of a program to another.

Program Using Try Throw and Catch

Program

#include<iostream.h>
#include<conio.h>
void main()
{
  try //trying to execute.
  {
    throw 20; //throwing 20.
  }
  catch(int e) //catching and storing in 'e'.
  {
    cout<<"An exception occurred. Exception Number: "<<e<<endl;
  }
getch();
}
Output
An exception occurred. Exception Number: 20

Program Using Multiple Try and Catch

Program

#include<iostream.h>
#include<conio.h>
void main()
{
try { //trying to execute.
        try //trying to execute.
        {
            throw 20; //throwing 20.
        }
        catch(int n) //catching.
        {
             cout<<"Handle Partially"<<endl;
             throw; //Re-throwing an exception.
        }
    }
    catch(int n) //catching.
    {
        cout<<"Handle remaining";
    }
getch();
}
Output
Handle Partially
Handle remaining