Exception in C++

Pages 703-720 in Lafore

 

Exception concepts

•      Exceptions are errors that occur at runtime

–   If they are not handled, they will crash your program

•      They are a way to separate

–   the code that deals with error conditions from

–   the code that executes when there are no errors.

•      Exceptions are not intended to be used as an alternative to normal data checking, since they have quite a bit of overhead.

 

Conditions that cause exception

•      Exceptions are caused by a wide variety of conditions, such as

–   Running out of memory

–   Not being able to open a file

–   Trying to initialize an object to an impossible value

–   Using an out-of-bounds index to an array

 

Exceptions use three new keywords

•   try – identifies a code block in which an exception occurs

•   throw – causes an exception condition to be originated

•   catch – identifies a block of code in which the exception is handled

 

Exception syntax

•      The programmer encloses in a try block the code that may generate an error

•      The try block is followed by one or more catch blocks

•      Each catch block specifies the type of exception it can handle

–    It contains the exception handler for that type of exception

•      If no handler is found, function terminate is called which calls function abort

•      If no exception is thrown, the catch block is not executed

 

 

int main( )

{   int height = 0;    char ch = 'y';

      const double InchesToMeters = 0.0254;
 while (ch =='y' || ch == 'Y')

      {     cout <<"Enter a height in inches: ";

            cin>>height;

            try

            {           if (height > 100)

                                    throw "Height exceeds max";

                        if (height < 9)

                                    throw "Height below minimum";

                        cout << static_cast<double>(height)*InchesToMeters

                                 << "meters"<<endl;

                        cout<<"Do you want to continue(y or n)? ";

                        cin>> ch;

            }

            catch (const char aMessage[ ])

            {           cout<<aMessage<<endl;                 }

     }

     return 0;   }

 

Specifying an exception class

•      Often an exception class is created just to have a type to throw

•      Example:

–   We have a stack class

–   If we try to push an item onto a full stack, we want to catch the exception

–   If we try to pop an empty stack, we also want to catch that exception

–   So we create an embedded exception class inside the stack class;

•   The body of this exception class is empty

 

Throwing an exception

•      A throw normally specifies an operand (the type of the operand is important)

•      The operand of a throw can be of any type

–   The type of the operand determines which exception handler (the catch block) will handle the exception

–   Each catch block is written to catch only exceptions of one type

 

Throwing an exception

•      Throwing an exception does two things:

–    1) transfers control to an exception handler of the correct type

–    2) Creates an temporary object of the type of the operand

•      Information can be communicated from the point of the exception to the exception handler

–    The information is the type of the thrown object, and

–    Information placed into the thrown object

•      The thrown object is typically a character string (for an error message) or a class object.

•      When the exception is thrown, control exits the try block and goes to the appropriate catch handler after that try block.

 

Catching an exception

•      Each catch block specifies a type it can catch, along with an optional parameter name.

•      When an exception is caught, the code in the catch block is executed

•      The catch block must immediately follow the try block.

•      After the code in the catch block is executed, execution continues with the next statement after the catch block

•      If an exception is not thrown by code in the try block (or any function called directly or indirectly in the try block) the catch block is ignored.

 

Exceptions with arguments

•      If the type thrown is a class, when the exception is thrown, the constructor of the class is called to create the object

•      This temporary object initializes the the parameter in the exception handler

•      If a parameter is named in the catch parameter

–   Then the parameter can be referenced in the handler

–   Otherwise information is not conveyed from the throw point to the handler

 

Example exceptions with arguments

•      We will use the Distance class for this

–   The data members are: int feet; float inches

–   The member functions are

•   Two constructors, one with no arguments, one with two

•   Void getdist( ) and void showdist( )

•      We will write an exception class that is thrown if inches is > 12

•      When the exception is thrown, the constructor for the exception class is called, initializing the data members

 

Exception class for class Distance

•      Two public data members

–   A string to indicate where the exception was thrown

–   A float to indicate what the bad inches value was

•      One member function: the constructor which has two arguments

•      Notice that now the place where the exception was called can be located, and other information is given to the user.

 

 

 

Stack unwinding

•      The throw statement starts a process called stack unwinding.

•      Any block or function is left as if there were a return statement.

•      For all local objects that are declared in the blocks that the program leaves due to the exceptions their destructors are called.

•      Stack unwinding continues until main( ) is exited, which ends the program, or until a catch clause “catches” and handles the exception.