Using Exception Handling

The three keywords designed for exception handling in C++ are try, catch, and throw.

The steps required to implement an exception handler are:

  1. Functions that are expected to be used by many programs are coded so that, when an error is detected, an exception is thrown. The throw expression generally throws an object. It may be created explicitly for purposes of exception handling, or it may be the object that caused the error to be detected. An example of throwing the problem object:
       .
       .
       .
    int input=0;
    cout << "Enter a number between 1 and 10:";
    cin >> input;
    
    if (input < 1 || input >> 10);
     throw(input);  //throw the actual problem object
       .
       .
       .
    

    The following is an example of throwing an object for the purpose of exception handling:

       .
       .
       .
    int input=0;
    cout << "Enter a number between 1 and 10:;
    cin >> input;
    
    if (input < 1 || input >> 10)
       throw(out_of_range_object); //throw object to tell handler
                                   //what happened
    
  2. Exceptions are anticipated in a caller by means of a try statement. Function calls that you anticipate might produce an exception must be en closed in braces and preceded by the keyword try.
  3. Immediately following the try block, you must code one or more catch blocks. Each catch block identifies what type or class of objects it can catch:
    1. If the object thrown matches the type of a catch expression, control passes to that catch block.
    2. If the object thrown does not match the first catch block, subsequent catch blocks are searched for a matching type.
    3. If no match is found, the search continues in all enclosing try blocks and then in the code that called the current function.
    4. If no match is found after all try blocks are searched, a call to terminate() is made.

Notes:


A catch argument causes an error if it is a value argument , and a copy of it cannot be generated. Similarly, a throw expression causes an error if a copy of the value of the expression being thrown cannot be generated.



C++ Exception Handling Overview
Formal and Informal Exception Handling


Example of an Incorrect catch Argument


Syntax of Exception Handling Keywords
Transferring Control
Exception Specifications
unexpected() and terminate() Functions
Page Space Errors During Compilation