on Leave a Comment

C++ Exception Handling

Exception is an abnormal behavior of a program. Exceptions arises during program run time and exceptions are unusual conditions arises when program is executing. C++ has a facility to detect and handle exceptions. Exception is a feature provided by ANSI C++

Assume, a program that accepts two number during run time and this program displays the result of division of those two numbers. If user enter zero as second number, then it is a exceptional situation and program stops responding. 

C++ exception handling has three keyword, namely, trythrow and catch

try: The statements which may generate exceptions are written under try block. When a exception is detected, it is thrown to catch block. A try block is followed by one or more catch block.

catch: A catch block is written just below the try block. In catch block, exception handling code is written. 

throw: When a exception is detected, it is thrown using throw keyword in try block.

The general form is:

......
......
......
try
{
       ......
       throw exception;
       ......
}
catch(type arg)
{
       ......
       ......
       ......
}
......
......
......

Examples of Exception Handing in C++

Example 1:

#include<iostream>
using namespace std;
int main()
{
    int x, y;
    cout<<"Enter two number: ";
    cin>>x>>y;

    try
    {
        if(y==0)
            throw ("You have zero as second number\nPlease enter another number");
        cout<<"Result is "<<x/y;
    }
    catch(const char *c)
    {
        cout<<c;;
    }
    return 0;
}

OUTPUT:

Enter two number: 5
0
You have zero as second number
Please enter another number

Example 2:

#include<iostream>
using namespace std;
void fun();
int main()
{
    int x, y;
    cout<<"Enter two number: ";
    cin>>x>>y;
    try
    {
        if(y==0)
           fun();
        cout<<"Result is "<<x/y;
    }
    catch(int e)
    {
        cout<<e;
    }
    catch(const char *c)
    {
        cout<<c;;
    }
    return 0;
}
void fun()
{
    throw ("You have zero as second number\nPlease enter another number");
}

OUTPUT:

Enter two number: 10
0
You have zero as second number
Please enter another number

Key Points:

(a) The catch block must be written just after the try block.

(b) There can be more than one catch block.

(c) A catch block can not written without try block, similarly a try block can't written without catch block

(d) catch block must accept the same type of argument as passed by the throw statement.

(e) If there are more than one catch block, then only catch block is selected by the type of argument passed by the throw statement.

(f) We can write more than one throw statement in a try block. 

(g) We must write some data after throw keyword.

(h) We can also write throw statement in a function, that is called in try block.

0 comments:

Post a Comment