Docstoc

exception

Document Sample
exception Powered By Docstoc
					                      EXCEPTION HANDLING(MADE EASY)

 An exception is defined as an abnormal event that disrupts the normal flow of a
 program. Exception handling, therefore, is the process of detecting and responding to
 exceptions in a consistent and reliable manner. The term "exception" is used instead of
 "error" because exceptions represent exceptional, or abnormal, conditions that aren't
 necessarily errors. In this way, an exception is a very general concept, meaning that any
 number of abnormal events could be interpreted as an exception.
 Exception handling in C++ enables a program to handle exceptional conditions in an
 organized manner. An exception is an abnormal behavior that could happen to your
 program. The ability to take care of such a behavior is called exception handling. If you
 write good instructions in your program and execute it, when a bad value is provided
 and the program behaves abnormally, the program is said to raise an exception.

When a try block throws an exception, the program control leaves the try block and
enters the catch statement of the catch block. Note that exceptions are objects used to
transmit information about a problem. If the type of object thrown matches the argument-
type in the catch statement, then catch block is executed for handling the exception. If it
does not match, the program is aborted with the help of the abort() function which is
invoked by default. When no exception is detected and thrown, the control goes to the
statement immediately after the catch block, i.e., the catch block is skipped. This is
shown in the program below:

An exception is an event, which occurs during the execution of a program, that disrupts
the normal flow of the program's instructions. When an error occurs within a method, the
method creates an object . The object, called an exception object, contains information
about the error, including its type and the state of the program when the error occurred.
Creating an exception object and handing it to the runtime system is called throwing an
exception.

After a method throws an exception, an attempt is made to find something to handle it.
The set of possible "somethings" to handle the exception is the ordered list of methods
that had been called to get to the method where the error occurred.

A search is made to find a method that contains a block of code that can handle the
exception. This block of code is called an exception handler. When an appropriate
handler is found, control passes the exception to the handler. An exception handler is
considered appropriate if the type of the exception object thrown matches the type that
can be handled by the handler.

The exception handler chosen is said to catch the exception. When no match is found, the
program terminates.

 Why Is Exception Handling Important?
 As there are many recent advances in software design, exception handling is meant
 more as a tool for improving the management of errors by providing a better approach
 to attacking the problem. The problem isn't so much that programmers don't know how
    to deal with errors or exceptional conditions; it's that every programmer has his or her
    own notion of how to go about doing it.

Types of exceptions:

Exceptions are of two kinds, namely, synchronous exceptions and asynchronous
exceptions. Errors such as "out-of-range index" and "over-flow" belong to the
synchronous type exceptions. The errors that are caused by events beyond the control of
the program (such as keyboard interrupts) are called asynchronous exceptions. The
proposed exception handling mechanism in C++ is designed to handle only synchronous
exceptions.

The purpose of the exception handling mechanism is to provide means to detect and
report an exceptional circumstance or condition, so that appropriate action can be taken
against it. The mechanism suggests a separate error handling code that performs the
following tasks:

         Find the problem (hit on the exception).
         Inform that an error has occurred (throw the exception).
         Receive the error information (catch the exception).
         Take corrective actions (handle the exception).

The error handling code basically consists of two segments; one to detect errors and to
throw exceptions, and the other to catch the exceptions and to take appropriate action.
Exception handling allows one section of a program to sense and dispatch error
conditions and another section to handle them.

try - C++ keyword that denotes an exception block

catch - C++ keyword that "catches" exceptions

throw - C++ keyword that "throws" exceptions

The „try„ block:

The functions that can detect and recover from errors execute from within a „try‟ block:

try

{

    //c++ statements

}

Code executing outside any try block cannot detect or handle exceptions. Try blocks may
be nested. The „try‟ block typically calls other functions that are able to detect exceptions.

The „catch‟ Exception handler
A catch exception handler with a parameter list follows a try block:

try

{

    //c++ statements

}

catch (int error)

{

//error handling code

}

There can be multiple catch handlers with different parameter lists

try

{

    //c++ statements

}

catch (int error)

{

//error handling code

}

catch (char *str)

{

//error handling code with char *

}

The „throw „ statement:

To detect an exception and jump to a catch handler , a c++ function issues the throw
statement with a data type that matches the parameter list of the proper catch handler:
throw “error occurred”;

This throw statement jumps to the catch exception handler function that has the char *
parameter list.

The throw statement unwinds the stack ,cleaning up all objects declared within the try
block by calling their destructors. Next , throw calls the matching catch handler, passing
the parameter object.

If u throw an exception for which there is no applicable catch statement, an abnormal
program termination may occur. Throwing an unhandled exception causes the standard
library function terminate() to be invoked. By default , terminate() calls abort() to stop
your program

void main()

{

        try

    {

            cout<<”inside try”;

             throw 100;

              cout<<”this will not execute”;

    }

        catch(int i)

    {

        cout<<”caught an exception no.”<<i;

        }

}

Output:

inside try

caught an exception no. 100

Explanation:
There is a „ try‟ block containing 3 statements and a catch(int i) statement that processes
an integer exception. Within the try block only 2 statements will get executed :the first
cout and the throw . Once an exception has been thrown , control passes to the catch
expression and the try block is terminated. However , often an error cannot be fixed and a
catch block will terminate the program with a call to exit() or abort(). The type of
exception must match the type specified in a catch statement. If u change the type in the
catch statement to double , the exception will not be called.

//exception handling demonstration

#include<iostream.h>

class exception{};

    void function()

{

    int error=1;

if(error)

{

        cout<<”throwing exception”<<endl;

    throw exception();

    }

}

void main()

{

          try

          {

          cout<<”calling function”<<”\n”;

          function();

         cout<<”retuing from function”<<”\n”;

           }

    catch(exception)
    {

          cout<<”catching exception”;

}

getch();

}

output:

calling function

throwing exception

catching exception

Explanation:

The program enters try block , that means that function() is being called from try block
The catch exception handler follows the try block . It catches exceptions that are thrown
by the exception class

An exception can be thrown from outside the try block as long as it is thrown by a
function that is called from within „try „ block

#include<iostream.h>

void function(int t)

{

        cout<<”inside function t is”<<t;

    if (t)

        throw t;

}

void main()

{

        try

    {
            cout<<”inside try”<<endl;

            function(0);

            function(1);

            function(2);

               }

        catch(int i)

    {

        cout<<”caught an exception no.”<<i;

        }

}

Output:

inside try

inside function t is 0

inside function t is 1

caught an exception no.1



Catch all statement:

//catch all demonstration

#include<iostream.h>

void function(int t)

{ try

    {

    if (t == 0 ) throw t;

    if (t == 1) throw „a‟;

    if (t == 2 ) throw 123.23;
     }

catch(int i)

{

    cout<<”caught integer\n”;

}

catch(…) //catch all other exceptions

{

    cout<<”caught one\n”;

}

}

void main()

{

         function(0);

         function(1);

         function(2);

getch();

}

output:

caught an integer

caught one

caught one

Explanation:

Using catch(…) as a default is a good way to catch all exceptions that u don‟t want to
handle explicitly. Also , by catching all exceptions , u prevent an unhandled exception
from causing an abnormal program termination

//catch all demonstration
#include<iostream.h>

class exception{};

    void function()

{

    int error=1;

if(error)

{

        cout<<”throwing exception”<<endl;

    throw exception();

    }

}

void main()

{

    try

{

                  try

              {

              cout<<”calling function”<<”\n”;

          function();

                    }

                  catch(…)

              {

                  cout<<”rethrowing exception\n”;

                  throw;

          }
}

    catch(exception)

    {

          cout<<”catching exception”;

}

getch();

}

output:

calling function

throwing exception

rethrowing exception

catching exception

Uncaught exceptions:

An uncaught exception is one for which there is no catch handler specified, or one thrown
by a destructor that is executing as the result of another throw. Such an exception causes
the terminate() function to be called , which calls the abort() function

//terminate() demonstration

#include<iostream.h>

class abc{};

class xyz{};

void function()

{

    int error=1;

if(error)

{

        cout<<”throwing xyz\n”;
    throw xyz();

    }

}

void main()

{

        try

        {

            cout<<”calling function\n”;

            function();

            }

        catch(abc)

        {

        cout<<”catching abc\n”;

            }

}

output:

calling function

throwing xyz

Abnormal program termination

The last line of the output depends upon what the compiler‟s abort() function displays
before it terminates the program

//terminate() function demonstration

#include<iostream.h>

class abc{};

class xyz{};
void main()

{

    try

    {

         cout<<”throwing uncaught exception\n”;

         throw xyz();

     }

     catch(abc)

     {

        cout<<”abc exception\n”;

        }

}



output:

throwing uncaught exception

Abnormal program termination

Explanation:

the statement throw xyz();

 raises an exception xyz for which no handler exists. Here , terminate() comes to rescue
this condition. When terminate() is called the program aborts by displaying the message:

Abnormal program termination

set_terminate()

set_terminate() function allows the user to install a function that defines the program‟s
actions to be taken to terminate the program when a handler for the exception cannot be
found.

// set_terminate() demonstration
#include<iostream.h>

#include<except.h>

class abc{};

class xyz{};

void myterminate()

{ cout<<”myterminate function invoked\n”;

    exit(1);

}

void main()

{

    set_terminate(myterminate);

    try

    {

         cout<<”throwing uncaught exception\n”;

         throw xyz();

     }

     catch(abc)

     {

        cout<<”abc exception\n”;

        }

}

output:

throwing uncaught exception

myterminate function is invoked
Raising an unspecified exception:

If a function throws an exception not listed in its specification , the program will call the
unexpected() function

#include<iostream.h>

class positive{};

class negative{};

void sign(int n) throw (positive, negative)

{

        if (n>0)

          throw positive();

         else

           if(n<0)

          throw negative();

else

throw zero(); // unspecified exception

}

void main()

{

        int n;

cout<<”enter a no\n”;

    cin>>n;

try

{

        sign(n);

    }
catch(positive)

{

     cout<<”+ve exception\n”;

}

catch(negative)

{

     cout<<”-ve exception\n”;

}

}

output:

enter a no. 0

Abnormal program termination

The prototype of the function sign() is specified as

void sign(int n) throw (positive, negative)

 this indicates that this function can raise positive and negative exceptions, but the
statement

    throw zero();

raises the exception zero, which is not in the exception list of this function. It calls the
default exception handler, which will abort the execution of the program



//division by zero exception

#include<iostream.h>

#include<conio.h>

void main()

{

     int a,b;
         cout<<”enter a and b”;

         cin>>a>>b;

         int x=a-b;

         try

         {

               If(x!=0)

               {

                        cout<<”result is”<<a/x;

                }

               else

               {

                           throw (x);

                    }

    }

         catch( int i)

     {

    cout<<”exception caught x is ”<<x;

        }

}

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:6
posted:11/24/2011
language:English
pages:16