Wednesday, March 28, 2018

Write a Program to rethrow an Exception


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;
}


Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home