In programming two most common types of error are logical error and syntax error.

The syntax error is detected during compilation of program, but the logical error will detect duringexecution of program. So, it is very difficult to handle logical error.

The exception handling provides mechanism to handle logical error during execution of program.

Steps to handle logical error:

1  .Find the problem (Hit the exception)

2.  Inform that an error has occurred (Throw the exception)

3.  Receive the error information (Catch the exception)

4.  Take corrective actions (Handle the exception)

Exception Handling Mechanism:

  • This mechanism is built upon three keyword: try, throw and catch.
  • try is used to preface a block of statement which may generate exceptions.
  • When an exception is detected, it is thrown using a throw statement.
  • A catch block is used to catches the exceptions thrown by throw statement and take appropriate action.
  • The relationship between try, throw and catch block is as shown in below figure.

Syntax:

try

{

    // Set of Statments;

    throw exception;

    // Set of Statements;

}

catch(type arg)

{

    // Set of Statements;

}

Example:

#include <iostream>
using namespace std;
int main()
{
    int a,b;
    cout<<”Enter the value of a and b ”;
    cin>>a>>b;
    try
    {
        if(b != 0)
            cout<<”The result(a/b)=”<<a/b;
        else
            throw(b);
    }
    catch(dividebyzeroException x)
    {
        cout<<”Exception caught b=”<<x;
    }
    return 0;
}