Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions...

24
Exception Handling Introduction •Exception handling is a mechanism to handle exceptions. •Exceptions are error like situations. •It is difficult to decide when error becomes an exception. •When an exception occurs, we need to provide an alternative path of execution. •In case where exception is not acceptable, we have to terminate the program.

Transcript of Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions...

Page 1: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Exception Handling

Introduction

•Exception handling is a mechanism to handle exceptions.•Exceptions are error like situations.•It is difficult to decide when error becomes an exception.•When an exception occurs, we need to provide an alternative path of execution.•In case where exception is not acceptable, we have to terminate the program.

Page 2: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Traditional Error handling

Traditionally error handling is done in three different ways

1) Returning error number

2) Global flag manipulation

3)Abnormal termination

None of them are completely suitable for solving problems.

Page 3: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

1) Returning Error Number

When we write a function we accept arguments and start processing. If something in the argument is wrong or something goes wrong while processing, the function returns an error code.

There is no universal standard for such error codes.

Ex:

1) Returning error code for wrong argument type ( int instead of double)

2) pointer argument which contains invalid address..

Page 4: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

2) Global Flag Manipulation

Library function set the value of errno ( global variable) to indicate error.

After calling library function, we can check the value of errno to find out actual error.

We can also use function perror() to get the same effect.

User should test the value of global flag every time the function is called otherwise user is in denger of getting unexpected results.

Page 5: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

3) Abnormal Termination Of The Program

Most common exception handling procedure.

Whenever something goes out of bound, we call exit() or abort().

But use of assert() function is better because it displays a message before terminating.

This is a very rough way to handle the situation and not at all orderly.

When we are dealing with objects, crashing the program without properly closing the files and resources held by the object can leave the system in inconsistent state. It is very difficult to recover from such state.

Page 6: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Need For Exception Handling

Exception handling mechanism is needed in c++ because of inappropriateness of all the traditional solutions while working with objects and in distributed environment.

Page 7: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Divide the error handling: The library Designer and Library User

While building a library, we may check for the error, but can not determine what to do with that error because of predetermining the way the library is going to be used is not possible since the library is actually built to be used in more than one situation.

The exception handling mechanism enables the library designer to throw exceptions and the library users to accept and handle those exceptions.

The error handling, thus, is divided. The library designer reports error and the user acts upon it.

Page 8: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Unconditional Termination and Programmer Preferred Termination

In case of abnormal termination of the program, the programmer does not have any control over the program-termination process.

The exception handling mechanism , by passing the control back to programmer, can provide termination controlled by the programmer, i.e., user can close the files and release buffers etc. before terminating.

Page 9: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Separating Error Reporting And Error Handling

The two conventional ways to do it are using error codes and using global error numbers. Both are not standardized.

In exception handling, we can have objects passed to the user, which can throw some more light on the situation related to the error.

Like, when reading a file, if the file is not available, it can provide functions which ask the user to select some other file instead or create a new file on the file.

Page 10: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

The Object Destroy Problem

When we define an object for a class with a dynamic constructor, we need a destructor.

When an object contains resources, we need a destructor to smoothly return the resources and close connections.

The exit or abort function do not call destructor of an object, so such objects which are not destroyed properly can create inconsistency.

If we use exception handling instead, the object destructors are automatically called and the problem is solved.

Page 11: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Components Of Exception Handling Mechanism

The exception handling mechanism has three building blocks:

Try : Indicating program area where exception can be thrown

Throw : Throwing an exception

Catch : Actually taking an action for the specific exception

Page 12: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Try :

The try block is the one which can throw an exception.

The code that we want to monitor for exceptions is placed within the try block.

Whenever we expect specific code segment to throw an exception, we place that segment within the try block.

Thus, a try block contains either a throw statement or a function containing either a throw statement or a similar function inside the body.

Page 13: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Catch:

In this section exception is handled.

Within the try block, by an explicit throw statement or by calling a function with such a throw statement, exception is said to be thrown.

The catch section should immediately follow the try block.

Page 14: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Throw:

This is mechanism to generate exception.

It is a single statement starting with the keyword throw.

The identifier following throw is a name of the variable being thrown.

The control now permanently transfers to the catch block and statements after throw statement are not executed.

Page 15: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

#include<iostream>

#include<conio.h>

#include<string>

using namespace std;

class myclass

{

public:

int no;

string str;

};

Page 16: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

void main()

{

try{

cout<<"Inside the try block\n";

cout<<"Throwing exception now\n";

myclass err;

err.no=0;

err.str="error";

if(err.no == 0)

throw err;

else

cout<<"this statement will not be executed if number is 0\n";}

Page 17: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

catch(myclass err)

{

cout<<"\nInside catch";

cout<<"\nNumber is:"<<err.no;

cout<<"\nString is:"<<err.str;

}

getch();

}

Page 18: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Terminate & Unexpected Functions

Terminate() is the function which calls abort() to exit the program in the event of run time error related to exceptions.

User can provide his or her own terminate() function instead of built-in terminate which just call abort and does nothing else.

From this function we may able to close all open files and de allocate resources before quitting the program.

Page 19: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

void myterminate()

{

//code to close file and de allocate resources will come //here

exit(-1);

}

void main()

{

void myterminate();

set_terminate(myterminate);

exgen();//this would generate exception for which no //catch available

cout<<“This will not be executed”;

}

Page 20: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

We can do all the clean up job like close files, de allocate dynamic memory, close connections if working in the client server, etc.

Similarly, for functions with exception specifications, if a function throws an exception which is not allowed, a function unexpected() is called, which in turn calls abort.

We can use set_unexpected (Name_of_own function) to provide our own function in such a case.

Page 21: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Uncaught Exception Functions

When an exception is thrown, it automatically invokes stack unwinding process.

In this process all the objects prior to the throw statement to the beginning of the try block are destroyed in the reverse order of their creation.

It is possible that some of the objects which are being destroyed have destructors. It is possible that destructor function might also throw an exception.

Page 22: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

If at least one of the object contains such a destructor, we have a situation where first exception is not completely handled, and the second is being thrown.

It is not possible in c++ to handle two exceptions simultaneously.

In such situations, a function from built-in exception class, uncaught_exception comes handy. It returns true when an exception is thrown.

If the destructor checks and finds that an exception has already been thrown when the destructor is called, the destructor will not throw a new one.

Page 23: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Exception And Debugger

.The role of debugger and the exception handling system clashes sometimes.

The debugger needs all the objects when an error occurs to indicate the user about the problem and the status of all those objects at that point of time.

On the other hand the exception handling system has to delete those objects because of compulsion to call the destructors.

Debugger must be aware of place where error has occurred and help the user out in such circumstances.

Page 24: Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.

Drawbacks Of Exception Handling

.1) Uncertain termination

2) Overhead

Exception handler is a tool for communication about anomalies between two different components of the program developed by two different individuals. This is not needed for checking normal error in a program.

All the users must be aware of the exceptions thrown by functions used by them. If it not possible, the exception handling approach will increase problem.