20
Exception Handling

Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

  • Upload
    others

  • View
    15

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

Exception Handling

Page 2: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

Occurs when a thrown exception is not caught in a particular scope

Unwinding a Function terminates that function

• All local variables of the function are destroyed

• Invokes destructors

• Control returns to point where function was invoked

Attempts are made to catch the exception in outer try…catch blocks

If the exception is never caught, the function terminate is called

Stack unwinding

Page 3: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

If exception is thrown in a try block (or in a function that is called from a try block or in a function that is called from a function that is called from a try block and so on), all local objects allocated from the runtime stack after the try block was entered are released (go out of scope) and their destructors are called. This process is called stack unwinding.

This process guarantees that when we try to recover from an error, there are no inconsistent data in the runtime stack and there is no memory leak

Stack unwinding

Page 4: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

Example

int main() { //.... try { Aclass myA; f1(); //.... } //catch come here }

void f1() { Bclass myB; f2(); //.... }

void f2() { Cclass myC; //.... throw "Exception"; }

Stack unwinding If error occurs in the function f2, the

destructors for objects myA, myB and

myC are called and those objects are

deleted from the stack in the reverse

order of creation and before the

exception is caught.

Note that this would also return any

dynamically allocated memory used in

those objects (myA, myB, myC),

through their properly implemented

destructors.

Page 5: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

Another example (problematic)

• Sometimes stack unwinding does not suffice since it does

not return the dynamic memory to heap.

try

{

int * myarr;

myarr = new int [LARGECLASS];

Process(myarr); //suppose an exception is thrown in Process function

}

catch (...)

{

//Need to free the heap memory pointed by myarr

//But there is a problem – cannot refer myarr

cout << "Exception caught" << endl;

}

Page 6: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

Another example (acceptable, but questionable solution)

• Move myarr definition outside the try block so that catch can refer.

• But this time you cannot force myarr pointer to go out of scope by stack unwinding.

int * myarr; //moved outside of try

try

{

myarr = new int [LARGECLASS];

Process(myarr); //suppose an exception is thrown in Process function

}

catch (...)

{

delete [] myarr;

cout << "Exception caught" << endl;

}

Page 7: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

Another example (best solution)

• Pure object oriented approach.

• Define a class for the array and let the class destructor to handle delete.

• Destructor of local objects are automatically called when exception is thrown but before it is caught (this is what stack unwinding is)

• CAUTION: You cannot refer to myarr in the catch block, not only due to scope rules, but also due to the fact it has been destructed when the exception is thrown.

try

{

ArrayClass myarr;

myarr.Init(); //allocates memory, etc.

myarr.Process(); //suppose an exception is thrown in Process function

}

catch (...)

{

cout << "Exception caught" << endl;

}

Page 8: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

Rethrowing an Exception

• Rethrowing exceptions

– Used when an exception handler cannot process an exception

– Rethrow exception with the statement:

throw;

• No arguments

• If no exception thrown in first place, calls terminate

– Handler can always rethrow exception, even if it performed some processing

– Rethrown exception detected by next enclosing try block

Page 9: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

• 1. Load header

• 1.1 Function prototype

#include <iostream> #include <exception> using std::cout; using std::endl; using std::exception; void throwException() { // Throw an exception and immediately catch it. try { cout << "Function throwException\n"; throw exception(); // generate exception } catch(exception e) { cout<<“Exception handled in function throw Exception\n”; }

Page 10: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

Function throwException

Exception handled in function throwException

Exception handled in main

Program control continues after catch in main

• 2. Function call

• 3. Output

• Program Output

throw; // rethrow exception for further processing } cout<< “This should not print\n”; } int main() { try { throwException( ); cout<< “This should not print\n”; } catch(exception e) { cout<<“Exception handled in main\n”; } cout<<“Program control continues after catch in main\n”; return 0; }

Page 11: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

Exception Specifications

Exception specification (throw list) means listed exceptions canbe thrown by a function Example: int g( double h ) throw ( a, b, c ) { // function body } Function can throw only listed exceptions or derived types If other type thrown, function unexpected called throw() (i.e., no throw list) states that function will not throw any exceptions In reality, function can still throw exceptions, but calls unexpected (more later) If no throw list specified, function can throw any exception

Page 12: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

• int someFunction( double value ) throw ( int, double) { ... }

The above example means the someFunction() can throw only int and double type of exception….

If others are thrown it will generate unexpected error.

Exception Specifications

Page 13: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

// Example 1(a) int Func(); // can throw anything\

// Example 1(b) int Gunc() throw(); // will throw nothing

int Hunc() throw(int , float); // can only throw int or double

Exception Specifications Example

Page 14: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

#include <iostream> #include <exception> #include <cstdlib> class X {}; class Y {}; class Z : public X {}; class W {}; void myunexpected() { cerr<<“Unexpected called”; throw “Hello”;} void f() throw(X, Y) { int n = 0; if (n) throw X(); // OK if (n) throw Z( ); // also OK throw W(); // will call std::unexpected() }

int main() { set_unexpected(myunexcepted) f( ); }

Exception Specifications Example

Page 15: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

Nesting try Blocks

• Exceptions are always handled by closest matching handler

try { try { throw 5; } catch (int x)‏

{ cout << x << endl; // exception will be caught here } } catch (int x)‏

{ cout << x-5 << endl; }

Page 16: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

Processing Unexpected Exceptions

• C++ has following functions to process unexpected exceptions that are not caught.

1) terminate()

2) abort()

Page 17: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

Processing Unexpected Exceptions

• Function unexpected – Calls the function specified with set_unexpected

• Default: terminate

• Function terminate – Calls function specified with set_terminate

• Default: abort

• set_terminate and set_unexpected – Prototypes in <exception>

– Take pointers to functions (i.E., Function name)

• Function must return void and take no arguments

– Returns pointer to last function called by terminate or unexpected

Page 18: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

#include <iostream> #include <exception> class one {}; class two {}; void main() { try { cout<<“\n An Uncaught Exception”; throw two( ); } catch(one) { cout<<“Excpetion for one”; } }

Here the program terminates as no Match is found for catch two, hence abort( ) function is called, implicitly

Processing Unexpected Exceptions

Page 19: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

Solution to the above problem is using :

• set_terminate and set_unexpected – Prototypes in <exception>

– Take pointers to functions which must be called to handle the exception (i.E., Function name)

• Function must return void and take no arguments

– Returns pointer to last function called by terminate or unexpected

Page 20: Exception Handling - WordPress.com · 29/06/2016  · Exception Handling . Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that

#include <iostream> #include <except> class one {}; class two {}; void skip() { cout<<“\n Function skip invoked”; } void main( ) {

set_terminate(skip); try { cout<<“\nThrowing Exception”; throw two(); } catch(one) { cout<<“Exception for one”; } }

..At this point function skip is invoked

Here the program instead of terminating when no Match is found for catch two, calls the function skip which is associated with set_terminate( ) function.

Processing Unexpected Exceptions