Using C++ Exceptions
C++ exceptions deal with the relationship of an application and a class member. When the application calls the class member and an error occurs, the class member informs the application of the error. The class member has done what is known as throwing an exception. The application takes this exception and handles it in a block of code called the catch block or the exception handler. It is in this block of code that the error can be dealt with and the program allowed to recover from this error. Taking a few steps back, the code that originally called the class member had to be included in a try block. The try block makes it possible to return the exception errors to the catch block. It is a guarded body of code that signifies what code is to return exception errors if they occur. Remem ber that code that does not interact with the class does not have to be in a try block.
There are three keywords for exception handling in C++:

  • try
  • catch
  • throw

try

A try block is a group of C++ statements, normally enclosed in braces { }, which may cause an exception. This grouping restricts exception handlers to exceptions generated within the try block.

catch

A catch block is a group of C++ statements that are used to handle a specific raised exception. Catch blocks, or handlers, should be placed after each try block. A catch block is specified by:

  • The keyword catch
  • A catch expression, which corresponds to a specific type of exception that may be thrown by the try block
  • A group of statements, enclosed in braces { }, whose purpose is to handle the exception

throw

The throw statement is used to throw an exception to a subsequent exception handler. A throw statement is specified with:

  • The keyword throw
  • An assignment expression; the type of the result of the expression determines which catch exception handler receives control

Example program for try-catch and throw
#include<iostream>
using namespace std;
int main()
{
   void func()
   {
     try
  {
                                   throw 1;
  }
  catch(int a)
  {
    cout << "Caught exception number:  " << a << endl;
    return;
  }
  cout << "No exception detected!" << endl;
    return;
}

}