Exception Handling:

In C++ programming, there occur unexpected errors or conditions; exception is a way of flagging such type of errors.

These error conditions are mostly handled by using an “if” statement by testing conditions or expressions. After this, a specific code is executed to deal with these errors.

It should be noted here that the exceptions are not intended to be used as an alternative to a normal data checking that may be done in the program. Exception should be used or applied near the disastrous conditions that might arise in the program. The keywords used in exception are try, throw and catch.

Throw: Program throws an exception.

Catch: Program catches an exception.

Try: Block of code for which a particular exception will be activated.

Consider the following example to understand the concept of exception handling.

EXAMPLE

# include <iostream>

using namespace std;

# include <conio.h>

class stack

{

private:

int array[2];

int top;

public:

stack();

void push (int d);

int pop ();

class empty {};

class exceeded {};

};

stack::stack()

{

array [top] = 0 ;

}

void stack :: push (int d)

{

if (top>=2)

  throw exceeded ();

else

  array[top] = d;

top++ ;

}

int stack :: pop ()

{

if (top <=0)

    throw empty();

else

   –top;

    return array [top];

}

void main ()

{

try

{

stack s;

  1. push (1);
  2. push (2);
  3. push (3);

cout << s.pop();

cout << s.pop();

cout << s. pop();

}

catch (stack :: exceeded )

{

cout <<”Buffer overflow”;

}

catch ( stack :: empty )

{

cout << “Buffer underflow”;

}

Working of the above program:

The above program is the stack program that has been discussed earlier. There is a modification in the program. We simple used exception handling to avoid overflow and underflow of the array variable.

The array has the 3 that is it can contain up to 3 elements. We used an exception in the function void push (int d) that if the index of array unexpectedly becomes greater than 2, it throws an exception exceeded. in the main () function there is a function catch which catches this exception and prints Buffer overflow.

Similarly when the array element becomes less than 0 or equal to 0 in the function int pop() an exception is called and caught by the catch function in the main () and prints Buffer underflow.

NOTE: elements of arrays becoming greater than 2 and less than equal to 0 i an exception and therefore, we used exception handling.

class empty {}; and class exceeded {}; are user defined exceptions.