Home Uncategorized Write a C++ Program to rethrow an Exception

Write a C++ Program to rethrow an Exception

SHARE

AIM: Write a Program to rethrow an Exception

Theory:
If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression (throwwithout assignment_expression) causes the originally thrown object to be rethrown.

Because the exception has already been caught at the scope in which the rethrow expression occurs, it is rethrown out to the next dynamically enclosing try block. Therefore, it cannot be handled by catch blocks at the scope in which the rethrow expression occurred. Any catch blocks for the dynamically enclosing try block have an opportunity to catch the exception.

Program:

#include<iostream>
using namespace std;
void sub(int i,int j)
{
    try
    {
        if(i==0)
        {
            throw i;
        }
        else
            cout<<“Subtraction result is: “<<i-j<<endl;
    }
    catch(int i)
    {
        cout<<“Exception caught inside sub()\n”;
        throw;
    }
};
int main()
{
    try
    {
        sub(8,4);
        sub(0,8);
    }
    catch(int k)
    {
        cout<<“Exception caught inside main()\n”;
    }
    return 0;
}

OUTPUT:

Subtraction result is: 4
Exception caught inside sub()
Exception caught inside main()

Back to Programs.