Docsity

Stack Unwinding - Object Oriented Programming - Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Stack Unwinding - Object Oriented Programming - Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming (OOP) Lecture No. 44

Example

class DivideByZero { public: DivideByZero() { } }; int Quotient(int a, int b){ if(b == 0){ throw DivideByZero(); } return a / b; }

Stack Unwinding

  • The flow control of throw is referred to as stack unwinding
  • Stack unwinding is more complex than return statement
  • Return can be used to transfer the control to the calling function only
  • Stack unwinding can transfer the control to any function in nested function calls

Stack Unwinding

  • All the local objects of a executing block are destroyed when an exception is thrown
  • Dynamically allocated memory is not destroyed automatically
  • If no catch handler catches the exception the function terminate is called, which by default calls function abort

Function-Call Stack

function2()

main()

function1()

function2() main()

main()

Stack Unwinding

  • The stack unwinding is also performed if we have nested try blocks

Stack Unwinding

  • Firstly the catch handler with float parameter is tried
  • This catch handler will not be executed as its parameter is of different type – no coercion
  • Secondly the catch handler with int parameter is tried and executed

Catch Handler

  • We can modify this to use the object to carry information about the cause of error
  • The object thrown is copied to the object given in the handler
  • Use the reference in the catch handler to avoid problem caused by shallow copy

Example

int Quotient(int a, int b) {

if(b == 0){ throw DivideByZero(a); } return a / b;

}

Body of main Function

for ( int i = 0; i < 10; i++ ) { try { GetNumbers(a, b); quot = Quotient(a, b); ... } catch(DivideByZero & obj) { obj.Print(); i--; } } cout << “\nSum of ten quotients is ” << sum;

Catch Handler

  • The object thrown as exception is destroyed when the execution of the catch handler completes

Avoiding too many Catch

Handlers

  • There are two ways to catch more then one object in a single catch handler - Use inheritance - Catch every exception

Grouping Exceptions

try{ ... } catch(DivideByZero){ ... } catch(IntergerOutOfRange){ ... } catch (InputStreamError){ }

Example–With Inheritance

try{

...

}

catch (MathError){

}

catch (InputStreamError){

}