Exception-Handling-in-C++ .

In this session i have discussed exception handling in C++ .


Exception is nothing but a condition that causes run time errors in program . i.e divide by zero . This exception can be handled by exception handling .

There are three keywords used for exception handling

1-try

2-catch

3-throw


1-Try

The try block is used to write the code which may causes error .

2-catch

The catch block is the block where exception can be handle .

3-Throw

The throw is used to send the exception to catch block .

Example : Write a program that demonstrate the exception handling .

    #include<iostream>
    using namespace std; 
    int main()
    {
        int x,y;
        cout<<"Enter the first number";
        cin>>x;
        cout<<"Enter the second number";
        cin>>y;
        try
        {
            if(y==0)
            {
                throw y;
            }
            cout<<"div : "<<x/y;
        }
        catch(int y)
        {
            cout<<"Number is divide by zero";
        }
        return 0;
    }
    OUTPUT : Enter the first number : 20   
             Enter the second number : 0
             Number is divide by zero
    

Example : Write a program that demonstrate the exception handling .

    #include<iostream>
    using namespace std; 
    class A
    {
        public :
        void div(int x,int y)
        {
            try
            {
                if(y==0)
                {
                    throw "divid by zero";
                }
                cout<<"div : "<<x/y;
            }
            catch(const char*e)
            {
                cerr<<e;
            }
        }
    };
    int main()
    {
        A obj;
        obj.div(20,0);

       return 0;
    }
    OUTPUT : Enter the first number : 20   
             Enter the second number : 0
             Number is divide by zero
    

In the above code i have used the cerr for displaying the error . It is used to display the error message on screen .

Welcome to AndroidATPoint.

back image                     next image