SlideShare a Scribd company logo
Oct 11, 2007 Handling Exceptions in C++ Dr. Partha Pratim Das Interra Systems (India) Pvt. Ltd.   PART B
Agenda PART A Exception Fundamentals Exceptions in C C Language Features C Standard Library Support SEH in Microsoft C Exceptions in C++ C++ Language Features try–catch–throw  Exception Specifications C++ Standard Library Support
Agenda PART B Exception Instrumentations in C++ How Compilers Manage Exceptional Flow? Designing with Exceptions in C++ Goals Scope Anatomy of a Function Meyers Guidelines
Agenda PART C Designing with Exceptions in C++  Analysis & Design of an Exception-safe stack Exception behavior of Standard Library Handling Exceptions in Multithreaded Environment TR1 Proposal
PART B
Exceptions Instrumentations in C++ How compilers manage Exceptional Flow
Exception Handling : Issues Code Isolation Separate Exceptions Flow from Normal Flow Separate Error Reporting from Error Handling  Efficiency Minimal Time Overhead for Normal Flow  Minimal Space Overhead for Normal Flow Optimization Minimize Loss of code optimizations under Exceptions Safety Contain the vulnerability of the Program
Function Call : Instrumentations Normal Flow return  Exceptional Flow with Stack Cutting setjmp / longjmp Exceptional Flow with Stack Unwinding try-catch-throw
Function Call : Items Normal Call Stack Frame Context Finalization  Stack Cutting Enhanced Stack Frame Exception Handler Frame Stack Unwinding Destructor Thunk EH Handler
Function Call Items : Stack Frame Function parameters  Function return address  Frame pointer  Local Objects Callee save registers
Function Call Items : Context Register PC / Return Address  (eip on x86) Register SP / Stack Pointer  (esp on x86) Register FP / Frame Pointer or Base Pointer  (ebp on x86)
Function Call Items : Finalization How are the right destructors called in the right order?  On Normal Exit On Exceptional Exit NOTE: This is tricky once the function has a multiple return statements before / after a number of local object constructions
Function Call : Normal Flow Caller prepares the Parameters Caller calls the Callee Callee saves the Context (Function Prologue) Callee does the job Callee restores the Context (Function Epilogue) Callee returns Caller cleans up the Parameters Caller uses the return value
Function Call Items : Stack Frame
Function Call Items : EH Frame
Function Call : Stack Cutting setjmp sets the jmp_buf buffer. #define _JBLEN  16 #define _JBTYPE int // Define jump buffer layout for x86 setjmp/longjmp. typedef struct __JUMP_BUFFER {      unsigned long Ebp;      unsigned long Ebx;      unsigned long Edi;      unsigned long Esi;      unsigned long Esp;      unsigned long Eip;      unsigned long Registration;      unsigned long TryLevel;      unsigned long Cookie;      unsigned long UnwindFunc;      unsigned long UnwindData[6]; } _JUMP_BUFFER; typedef _JBTYPE jmp_buf[_JBLEN];
Function Call : Stack Cutting longjmp forces the context (FP, SP and PC) to the jmp_buf buffer stored at setjmp point. Effect is – control resurfaces in setjmp and longjmp never returns. Stack is ‘CUT’: Local objects are not finalized All intervening frames are trashed
Function Call Items : Stack Frame
Function Call Items : Thunk A delayed computation Runtime registers a destructor thunk for the exception object. Catch handler calls the thunk at end.
Function Call Items : EH Handler
Function Call : Stack Unwinding Flow: Creation of Exception object Placement of destructor thunk for Exception object Wrapping up of the stack frame. Calling of Finalizers – ‘UNWIND’ Matching for Handler  Catch handlers are statically overloaded but dynamically dispatched.  Explain why this will need RTTI.
Function Call : Stack Unwinding Flow: Invocation of the right handler. Exit from the handler  Invocation of the thunk if no rethrow has been done.
Function Call : Stack Unwinding Data Structures: Stack Frame RUNTIME_FUNCTION UNWIND_INFO TRY_REGION_TABLE CLEANUP_TABLE
Exception Handling : Trade Off
Designing with Exceptions in C++ Glimpses of Design Issues
Designing with Exceptions : Goals “ With Exceptions” !!! Designing  in spite of  Exceptions? Designing  with the help of  Exceptions? Both.
Designing with Exceptions : Goals Graded Goals Do Nothing No Crash No Resource Leak Valid System State Unchanged System State Works ALWAYS No Safety Minimal Safety Basic Safety Strong Safety No-Throw Safety
Exception Safety : Levels No Exception Safety No guarantees are made.  This is never acceptable in a production environment. Minimal Exception Safety Partial execution of failed operations may store invalid data but will not cause a crash.  This may be acceptable for a graceful exit. Basic Exception Guarantee Partial execution of failed operations can cause side effects Invariants on the state are preserved  Any stored data will contain valid values.
Exception Safety : Levels Strong Exception Guarantee (Commit or Rollback)  Failed operations are guaranteed to have no side effects.  Operations either succeed or have no effect at all. No-Throw Guarantee (Failure Transparency) Operations are guaranteed to succeed and satisfy all requirements even in presence of exceptional situations.  Ideal; but may be unrealistic.  Usually not possible in libraries where complete knowledge of the application is not available.
Designing with Exceptions : Scope We Consider: Function Calls Global Functions Static Methods Non-Static Methods Virtual Functions Operators (Overloaded) Objects Automatic Dynamic
Designing with Exceptions : Scope We do not consider: Static Objects Asynchronous Exceptions Standard Library Objects STL Containers …
C++ Ground Rules : Lifetime When does an object's lifetime begin? When its constructor completes successfully and returns normally.  When does an object's lifetime end? When its destructor begins.  What is the state of the object after its lifetime has ended? There is no object.
C++ Ground Rules : Lifetime Construction: An object is considered  fully constructed  when the control goes out of constructor. Destruction: C++ refuses to call destructors for objects that haven't been fully constructed   When an object is destructed, all fully constructed sub-objects are destructed. Finalization:  Destructors for all local objects are called on exit (except for abort(), exit() and longjmp()).
Anatomy of a Function Safe Operations Operations with built-in types Compiler Mechanisms Call, Return, Try, Throw, Catch Safe Functions Unsafe Operations Functions Construction Copy Construction Copy Assignment Destruction operator new / delete … class A { }; A Viscera( A x , // Argument Copy A& rx ,  A* px )  { // Local objects A a ; A& ra =   *px ; A* pa =   new A(rx) ; try { // ... // Parameter Copy A a =  // Return Value Copy Viscera( a ,  *pa ,  &ra ); // ... } catch ( A& e ) { // Handler } //  Exception Destructor Thunk // Exception Object Copy throw  x ; // Exception Exit // Temporary Object Copy return  a ; // Normal Exit } //  Local Object Cleanup
Exceptional Design Rules Meyers’ Recommendations on Basic Exception Safety
Exception Safety :  Meyers Guidelines Item 9:  Use destructors to prevent resource leaks   Item 10:  Prevent resource leaks in constructors   Item 11:  Prevent exceptions from leaving destructors   Item 12:  Understand how throwing an exception differs from passing a parameter or calling a virtual function   Item 13:  Catch exceptions by reference   Item 14:  Use exception specifications judiciously   Item 15:  Understand the costs of exception handling  
Meyers [9] :  Use destructors to prevent resource leaks Situation   A hierarchy of Polygonal objects Two methods: Poly* readPoly(istream&) Read from input stream, and  Create (through factory). virtual void plotPoly() Object drawn on the plotter device Poly Quad Tri
Meyers [9] :  Use destructors to prevent resource leaks Classes class Poly { public:  virtual void plotPoly() = 0;  ... };  class Quad: public Poly { public:  virtual void plotPoly();  ... };  class Tri: public Poly { public:  virtual void plotPoly();  ... };
Meyers [9] :  Use destructors to prevent resource leaks plot() for the Graphic Device (unsafe) void plot(istream& myStream) {  // while there's data   while (myStream) { // get next poly  Poly *pPoly = readPoly(myStream); // Plot the polygon pPoly->plotPoly();    // delete object that  // readPoly returned  delete pPoly;  }  }   plotPoly() throws    *pPoly leaks
Meyers [9] :  Use destructors to prevent resource leaks plot() for the Graphic Device (safe) void plot(istream& myStream) {    // while there's data   while (myStream) { // get next poly  Poly *pPoly = readPoly(myStream); try { // Plot the polygon pPoly->plotPoly();    } catch (...) { // delete object - exception delete pPoly; throw; // passes on exception } // delete object – no exception delete pPoly;  }  }   Code Duplication
Meyers [9] :  Use destructors to prevent resource leaks Litter code with try and catch blocks.  Duplicate cleanup code Normal paths and  Exceptional paths.  Executes anyway! Move the cleanup code that must always be executed into the destructor for an object local to plot().  Local objects are always destroyed when leaving a function, regardless of how that function is exited.  The solution is to replace the pointer with an object that  acts like  a pointer aka,  Smart Pointer
Meyers [9] :  Use destructors to prevent resource leaks Smart pointer  Is a C++ object  Stores pointers to dynamically allocated (heap / free store) objects Improves raw pointers by implementing  Construction & Destruction Copying & Assignment Dereferencing: operator–>  operator* Grossly  mimics raw pointer syntax & semantics
Meyers [9] :  Use destructors to prevent resource leaks auto_ptr template<class T>  class auto_ptr {  public:  // save ptr to object  auto_ptr(T *p = 0): ptr_(p) {} // delete ptr to object  ~auto_ptr() { delete ptr_; } // Indirection  T* operator->() const { return ptr_; }  ... private:  // raw ptr to object  T *ptr_;  };
Meyers [9] :  Use destructors to prevent resource leaks plot() for the Graphic Device (safe) void plot(istream& myStream) {  // while there's data   while (myStream) { // get next poly  auto_ptr<Poly> pPoly(readPoly(myStream)); // Plot the polygon pPoly->plotPoly();    }  }   pPoly->plotPoly();  means   (pPoly.operator->())->plotPoly();
Meyers [9] :  Use destructors to prevent resource leaks Smart Pointers work as Holders of Resources RAII – Resource Acquisition is Initialization Idiom  Scoped Acquisition – Release Paradigm Acquires / Locks in Constructor  Releases / Unlocks in Destructor Ensures safety on face of exceptions
Meyers [9] :  Use destructors to prevent resource leaks Window Handling in Windows OS (unsafe) // This function leaks resources  // if an exception is thrown  void Display(const Information& info) {  HANDLE w = CreateWindow( /* Creation Parameters */ );  /* Data preparations */ RenderWindow(w, info, /* Display Parameters */);  /* Data Cleanup */ DestroyWindow(w);  }
Meyers [9] :  Use destructors to prevent resource leaks Window Holder // class for Holding (acquiring and  // releasing) a window handle  class WindowHolder {  public:  WindowHolder(HANDLE h): w_(h) {}  ~WindowHolder() { DestroyWindow(w_); }  operator HANDLE() { return w_; } private:  HANDLE w_;  // Stop free functions being available  WindowHolder(const WindowHolder&);  WindowHolder& operator=(const WindowHolder&);  };
Meyers [9] :  Use destructors to prevent resource leaks Window Handling in Windows OS (safe) // This function cleans up resources -  always void Display(const Information& info) {  WindowHolder  w(CreateWindow( /* Creation Parameters */ ));  /* Data preparations */ // WindowHandle is implicitly converted to HANDLE RenderWindow(w, info, /* Display Parameters */);  /* Data Cleanup */ }
Meyers [9] :  Use destructors to prevent resource leaks Morale Resources should be encapsulated inside objects.  Usually avoids resource leaks in the face of exceptions.
More Questions   What happens if an exception is thrown in the process of acquiring a resource, that is, in the  constructor  of a resource-acquiring class?  What happens if an exception is thrown during the automatic  destruction  of such resources?
Meyers [10] :  Prevent resource leaks in constructors   Consider:  class T { ... };  class T1 { public: T1(const T&); ... };  class T2 { public: T2(const T&); ... };  class A {  public:  A(const T&, const T& = (T)0, const T& = (T)0);  ~A();  void f(const T&); ...  private:  T  m_;  T1 *p1_;  T2 *p2_;  };
Meyers [10] :  Prevent resource leaks in constructors   Constructor (unsafe) / Destructor:  A::A(const T& d, const T& s1, const T& s2): m_(d), p1_(0), p2_(0) { if (s1 != (T)0) p1_ = new T1(s1); //  1 if (s2 != (T)0)  p2_ = new T2(s2); //  2 } A::~A() {  delete p1_; delete p2_’ }
Meyers [10] :  Prevent resource leaks in constructors   Exception in body: operator (T)  may throw. T::operator !=  may throw T::operator new  may throw  bad_alloc Constructor for  T1  or  T2  may throw Exception at Line 1 is safe.  m_  gets destructed. Exception at Line 2 leaks  p1_ .  A::~A() does not get called as the object is not there. A::A(const T& d, const T& s1, const T& s2):m_(d), p1_(0), p2_(0) { if (s1 != (T)0) p1_ = new T1(s1); //  Line 1 if (s2 != (T)0) p2_ = new T2(s2); //  Line 2  }
Meyers [10] :  Prevent resource leaks in constructors   Try Exception Fix by Dynamic Allocation Doesn’t work as  pA  is never assigned if the following throws T::operator new Constructor for  A {  A *pA = 0;  try {  pA = new A(d, s1, s2);  ...  } catch (...) { // catch all exceptions delete pA;  // delete pA on an exception throw;  // Rethrow exception } delete pA;  // delete pA normally  }
Meyers [10] :  Prevent resource leaks in constructors   Constructor (safe) cleans up itself A::A(const T& d, const T& s1, const T& s2): m_(d), p1_(0), p2_(0) { try { if (s1 != (T)0) p1_ = new T1(s1); //  1 if (s2 != (T)0)  p2_ = new T2(s2); //  2 } catch (...) { delete p1_; delete p2_; throw; } } A::~A() {  delete p1_; delete p2_’ }
Meyers [10] :  Prevent resource leaks in constructors   Constructor (safe): w/o code duplication A::A(const T& d, const T& s1, const T& s2): m_(d), p1_(0), p2_(0) { try { if (s1 != (T)0) p1_ = new T1(s1); //  1 if (s2 != (T)0)  p2_ = new T2(s2); //  2 } catch (...) { CleanUp(); throw; } } A::~A() {  CleanUp(); } A::CleanUp() {  delete p1_; delete p2_; }
Meyers [10] :  Prevent resource leaks in constructors   Reconsider:  class T { ... };  class T1 { public: T1(const T&); ... };  class T2 { public: T2(const T&); ... };  class A {  public:  A(const T&, const T& = (T)0, const T& = (T)0);  ~A();  void f(const T&); ...  private:  T  m_;  T1 *  const  p1_;  T2 *  const  p2_;  };
Meyers [10] :  Prevent resource leaks in constructors   Constructor (unsafe):  Exception at Line 1 is safe.  m_  gets destructed. Exception at Line 2 leaks  p1_ .  A::~A() does not get called. No try-catch on Initializer list – only expressions.  A::A(const T& d, const T& s1, const T& s2): m_(d),  p1_((s1 != (T)0)? new T1(s1): 0),  // Line 1 p2_((s2 != (T)0)? new T2(s2): 0)  // Line 2 { }
Meyers [10] :  Prevent resource leaks in constructors   Constructor (safe):  T1* A::InitT1(const T&s) { if (s != (T)0) return new T1(s); else return (T1*)0; } T2* A::InitT2(const T&s) { try { if (s != (T)0) return new T2(s); else return (T2*)0;  } catch (...) { delete p1_; throw; } } A::A(const T& d, const T& s1, const T& s2): m_(d), p1_(InitT1(s1)), p2_(InitT2(s2)) { }
Meyers [10] :  Prevent resource leaks in constructors   A better design:  class T { ... };  class T1 { public: T1(const T&); ... };  class T2 { public: T2(const T&); ... };  class A {  public:  A(const T&, const T& = (T)0, const T& = (T)0);  ~A();  void f(const T&); ...  private:  T  m_;  const auto_ptr<T1> p1_;  const auto_ptr<T2> p2_;  };
Meyers [10] :  Prevent resource leaks in constructors   Constructor (safe by design):  Exception at Line 1 is safe.  m_  gets destructed. Exception at Line 2 is safe.  m_  &  p1_  get destructed. // Constructor A::A(const T& d, const T& s1, const T& s2): m_(d),  p1_((s1 != (T)0)? new T1(s1): 0),  // Line 1 p2_((s2 != (T)0)? new T2(s2): 0)  // Line 2 { } // Destructor A::~A() { }
Meyers [10] :  Prevent resource leaks in constructors Moral Replace pointer class members with their corresponding auto_ptr objects Fortifies constructors against resource leaks in the presence of exceptions,  Eliminates the need to manually deallocate resources in destructors, and  Allows const member pointers to be handled in the same graceful fashion as non-const pointers.
Meyers [11] :  Prevent exceptions from leaving destructors   A destructor is called in two situations  When an object is destroyed under “normal” conditions When it goes out of scope or  Is explicitly deleted.  When an object is destroyed by the exception-handling mechanism during the stack-unwinding part of “exception propagation”.
Meyers [11] :  Prevent exceptions from leaving destructors   Recap  If an exception is thrown when another exception is active,  terminate()  is called and the program  immediately  terminates. From within a destructor, there is no robust way to determine if an exception is active.
Meyers [11] :  Prevent exceptions from leaving destructors   Consider  class Session {  public:  Session();  ~Session();  ...  private:  static void logCreation(Session *);  static void logDestruction(Session *);  };   Session::~Session() { // Fatal to throw here logDestruction(this);  };
Meyers [11] :  Prevent exceptions from leaving destructors   Manage the exceptions  Session::~Session() { try { logDestruction(this); } catch (...) {  // Fatal again if operator<<() throws cerr << &quot;Unable to log destruction of Session object&quot;  << &quot;at address &quot;  << this  << &quot;.\n&quot;;  }  };
Meyers [11] :  Prevent exceptions from leaving destructors   Bite the dust – swallow the exceptions  Session::~Session() { try { logDestruction(this); } catch (...) { }  };
Meyers [11] :  Prevent exceptions from leaving destructors   Moral  Keep exceptions from propagating out of destructors.  Prevents terminate from being called during the stack-unwinding part of exception propagation.  Helps ensure that destructors always accomplish everything they are supposed to accomplish.
Meyers [12] :  Throwing an exception differs from passing a parameter or calling a virtual function  Control does not return to the throw site. Throw always copies the object. Catch needs to clean-up the thrown object. Parameter Matching is exact for Catch and done with the static type Overloaded Catch clauses are tried in lexical order.
Meyers [13] :  Catch exceptions by reference
Meyers [14] :    Use exception specifications judiciously
Meyers [15] :    Understand the costs of exception handling
Handling Exceptions in  C & C++ References & Credits
References Handling Exceptions: Part 1 – 4 Robert Schmidt Modern C++ Design: Generic Programming & Design Pattern Applied  Andrei Alexandrescu Exceptional C++ & More Exceptional C++  Herb Sutter  Effective C++ & More Effective C++ Scott Meyers Standard Features Missing From VC++ 7.1. Part I: Exception Specifications  Nemanja Trifunovic  http://www.codeproject.com/cpp/stdexceptionspec.asp   A Pragmatic Look at Exception Specifications http://www.gotw.ca/publications/mill22.htm
Credits / Acknowledgements
Thank You

More Related Content

PPT
Handling Exceptions In C &amp; C++[Part A]
PDF
C++ exception handling
PDF
EXCEPTION HANDLING in C++
PPTX
CodeChecker summary 21062021
PDF
Exception Handling in the C++ Constructor
PDF
Tesseract. Recognizing Errors in Recognition Software
PDF
c++ lab manual
PPT
Verilog Lecture4 2014
Handling Exceptions In C &amp; C++[Part A]
C++ exception handling
EXCEPTION HANDLING in C++
CodeChecker summary 21062021
Exception Handling in the C++ Constructor
Tesseract. Recognizing Errors in Recognition Software
c++ lab manual
Verilog Lecture4 2014

What's hot (19)

PDF
C++ idioms by example (Nov 2008)
PDF
Insecure coding in C (and C++)
PPTX
Java - Generic programming
PDF
Exceptions and Exception Handling in C++
PPT
C tutorial
PPT
C tutorial
PDF
Checking the Source Code of FlashDevelop with PVS-Studio
PPTX
PPT
C Tutorials
PPTX
Overview of c++ language
PPT
F6dc1 session6 c++
PPT
Paradigmas de Linguagens de Programacao - Aula #4
PPTX
The operation principles of PVS-Studio static code analyzer
PDF
RAII and ScopeGuard
PPT
Verilog Lecture2 thhts
DOCX
C++ lab assignment
PDF
2 debugging-c
PDF
Oop10 6
PDF
C++ boot camp part 1/2
C++ idioms by example (Nov 2008)
Insecure coding in C (and C++)
Java - Generic programming
Exceptions and Exception Handling in C++
C tutorial
C tutorial
Checking the Source Code of FlashDevelop with PVS-Studio
C Tutorials
Overview of c++ language
F6dc1 session6 c++
Paradigmas de Linguagens de Programacao - Aula #4
The operation principles of PVS-Studio static code analyzer
RAII and ScopeGuard
Verilog Lecture2 thhts
C++ lab assignment
2 debugging-c
Oop10 6
C++ boot camp part 1/2
Ad

Viewers also liked (14)

PPT
Exception handling in c++ by manoj vasava
PPSX
Exception Handling
PPT
Handling
PPTX
Chp3(pointers ref)
PPTX
Pointers in c++
PDF
05 c++-strings
PPTX
String in programming language in c or c++
PPTX
String Handling in c++
PPTX
Exception Handling in C++
PPT
Exception handling and templates
PPT
Strings
PDF
Pointer in c++ part1
PPTX
Exception handling
PPTX
Pointer in C++
Exception handling in c++ by manoj vasava
Exception Handling
Handling
Chp3(pointers ref)
Pointers in c++
05 c++-strings
String in programming language in c or c++
String Handling in c++
Exception Handling in C++
Exception handling and templates
Strings
Pointer in c++ part1
Exception handling
Pointer in C++
Ad

Similar to Handling Exceptions In C &amp; C++ [Part B] Ver 2 (20)

PPTX
2. Design patterns. part #2
ZIP
PPT
.Net Garbage Collector 101
PPTX
ppl unit 3.pptx ppl unit 3 usefull can understood
PPTX
C# 6.0 Preview
PDF
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...
PPTX
Scope Stack Allocation
PPTX
Introduction to c_plus_plus (6)
PPTX
Introduction to c_plus_plus
PPT
C++tutorial
DOCX
Memory management in c++
PDF
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
PPTX
Lec05 buffers basic_examples
PPTX
C++ Core Guidelines
PDF
JVM Mechanics: When Does the JVM JIT & Deoptimize?
PDF
Beyond Breakpoints: A Tour of Dynamic Analysis
PPTX
Lambdas puzzler - Peter Lawrey
PDF
C++ Training
PDF
C++aptitude questions and answers
PDF
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
2. Design patterns. part #2
.Net Garbage Collector 101
ppl unit 3.pptx ppl unit 3 usefull can understood
C# 6.0 Preview
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...
Scope Stack Allocation
Introduction to c_plus_plus (6)
Introduction to c_plus_plus
C++tutorial
Memory management in c++
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
Lec05 buffers basic_examples
C++ Core Guidelines
JVM Mechanics: When Does the JVM JIT & Deoptimize?
Beyond Breakpoints: A Tour of Dynamic Analysis
Lambdas puzzler - Peter Lawrey
C++ Training
C++aptitude questions and answers
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova

More from ppd1961 (20)

PDF
Land of Pyramids, Petra, and Prayers - Egypt, Jordan, and Israel Tour
PDF
Science & Culture Article with Editorial & Cover
PDF
NDL @ YOJANA
PPT
Unified Modeling Language (UML)
PPT
OOP in C++
PDF
Digital geometry - An introduction
PDF
Innovation in technology
PPTX
Kinectic vision looking deep into depth
PDF
C++11
DOC
Function Call Optimization
DOC
How To Define An Integer Constant In C
PPT
Stl Containers
PPT
Object Lifetime In C C++
PPT
Technical Documentation By Techies
PPT
Vlsi Education In India
PPT
Reconfigurable Computing
PPT
Women In Engineering Panel Discussion
PPT
Dimensions of Offshore Technology Services
PPT
Concepts In Object Oriented Programming Languages
PPT
Glimpses of C++0x
Land of Pyramids, Petra, and Prayers - Egypt, Jordan, and Israel Tour
Science & Culture Article with Editorial & Cover
NDL @ YOJANA
Unified Modeling Language (UML)
OOP in C++
Digital geometry - An introduction
Innovation in technology
Kinectic vision looking deep into depth
C++11
Function Call Optimization
How To Define An Integer Constant In C
Stl Containers
Object Lifetime In C C++
Technical Documentation By Techies
Vlsi Education In India
Reconfigurable Computing
Women In Engineering Panel Discussion
Dimensions of Offshore Technology Services
Concepts In Object Oriented Programming Languages
Glimpses of C++0x

Handling Exceptions In C &amp; C++ [Part B] Ver 2

  • 1. Oct 11, 2007 Handling Exceptions in C++ Dr. Partha Pratim Das Interra Systems (India) Pvt. Ltd. PART B
  • 2. Agenda PART A Exception Fundamentals Exceptions in C C Language Features C Standard Library Support SEH in Microsoft C Exceptions in C++ C++ Language Features try–catch–throw Exception Specifications C++ Standard Library Support
  • 3. Agenda PART B Exception Instrumentations in C++ How Compilers Manage Exceptional Flow? Designing with Exceptions in C++ Goals Scope Anatomy of a Function Meyers Guidelines
  • 4. Agenda PART C Designing with Exceptions in C++ Analysis & Design of an Exception-safe stack Exception behavior of Standard Library Handling Exceptions in Multithreaded Environment TR1 Proposal
  • 6. Exceptions Instrumentations in C++ How compilers manage Exceptional Flow
  • 7. Exception Handling : Issues Code Isolation Separate Exceptions Flow from Normal Flow Separate Error Reporting from Error Handling Efficiency Minimal Time Overhead for Normal Flow Minimal Space Overhead for Normal Flow Optimization Minimize Loss of code optimizations under Exceptions Safety Contain the vulnerability of the Program
  • 8. Function Call : Instrumentations Normal Flow return Exceptional Flow with Stack Cutting setjmp / longjmp Exceptional Flow with Stack Unwinding try-catch-throw
  • 9. Function Call : Items Normal Call Stack Frame Context Finalization Stack Cutting Enhanced Stack Frame Exception Handler Frame Stack Unwinding Destructor Thunk EH Handler
  • 10. Function Call Items : Stack Frame Function parameters Function return address Frame pointer Local Objects Callee save registers
  • 11. Function Call Items : Context Register PC / Return Address (eip on x86) Register SP / Stack Pointer (esp on x86) Register FP / Frame Pointer or Base Pointer (ebp on x86)
  • 12. Function Call Items : Finalization How are the right destructors called in the right order? On Normal Exit On Exceptional Exit NOTE: This is tricky once the function has a multiple return statements before / after a number of local object constructions
  • 13. Function Call : Normal Flow Caller prepares the Parameters Caller calls the Callee Callee saves the Context (Function Prologue) Callee does the job Callee restores the Context (Function Epilogue) Callee returns Caller cleans up the Parameters Caller uses the return value
  • 14. Function Call Items : Stack Frame
  • 15. Function Call Items : EH Frame
  • 16. Function Call : Stack Cutting setjmp sets the jmp_buf buffer. #define _JBLEN  16 #define _JBTYPE int // Define jump buffer layout for x86 setjmp/longjmp. typedef struct __JUMP_BUFFER {      unsigned long Ebp;     unsigned long Ebx;     unsigned long Edi;     unsigned long Esi;     unsigned long Esp;     unsigned long Eip;     unsigned long Registration;     unsigned long TryLevel;     unsigned long Cookie;     unsigned long UnwindFunc;     unsigned long UnwindData[6]; } _JUMP_BUFFER; typedef _JBTYPE jmp_buf[_JBLEN];
  • 17. Function Call : Stack Cutting longjmp forces the context (FP, SP and PC) to the jmp_buf buffer stored at setjmp point. Effect is – control resurfaces in setjmp and longjmp never returns. Stack is ‘CUT’: Local objects are not finalized All intervening frames are trashed
  • 18. Function Call Items : Stack Frame
  • 19. Function Call Items : Thunk A delayed computation Runtime registers a destructor thunk for the exception object. Catch handler calls the thunk at end.
  • 20. Function Call Items : EH Handler
  • 21. Function Call : Stack Unwinding Flow: Creation of Exception object Placement of destructor thunk for Exception object Wrapping up of the stack frame. Calling of Finalizers – ‘UNWIND’ Matching for Handler Catch handlers are statically overloaded but dynamically dispatched. Explain why this will need RTTI.
  • 22. Function Call : Stack Unwinding Flow: Invocation of the right handler. Exit from the handler Invocation of the thunk if no rethrow has been done.
  • 23. Function Call : Stack Unwinding Data Structures: Stack Frame RUNTIME_FUNCTION UNWIND_INFO TRY_REGION_TABLE CLEANUP_TABLE
  • 24. Exception Handling : Trade Off
  • 25. Designing with Exceptions in C++ Glimpses of Design Issues
  • 26. Designing with Exceptions : Goals “ With Exceptions” !!! Designing in spite of Exceptions? Designing with the help of Exceptions? Both.
  • 27. Designing with Exceptions : Goals Graded Goals Do Nothing No Crash No Resource Leak Valid System State Unchanged System State Works ALWAYS No Safety Minimal Safety Basic Safety Strong Safety No-Throw Safety
  • 28. Exception Safety : Levels No Exception Safety No guarantees are made. This is never acceptable in a production environment. Minimal Exception Safety Partial execution of failed operations may store invalid data but will not cause a crash. This may be acceptable for a graceful exit. Basic Exception Guarantee Partial execution of failed operations can cause side effects Invariants on the state are preserved Any stored data will contain valid values.
  • 29. Exception Safety : Levels Strong Exception Guarantee (Commit or Rollback) Failed operations are guaranteed to have no side effects. Operations either succeed or have no effect at all. No-Throw Guarantee (Failure Transparency) Operations are guaranteed to succeed and satisfy all requirements even in presence of exceptional situations. Ideal; but may be unrealistic. Usually not possible in libraries where complete knowledge of the application is not available.
  • 30. Designing with Exceptions : Scope We Consider: Function Calls Global Functions Static Methods Non-Static Methods Virtual Functions Operators (Overloaded) Objects Automatic Dynamic
  • 31. Designing with Exceptions : Scope We do not consider: Static Objects Asynchronous Exceptions Standard Library Objects STL Containers …
  • 32. C++ Ground Rules : Lifetime When does an object's lifetime begin? When its constructor completes successfully and returns normally. When does an object's lifetime end? When its destructor begins. What is the state of the object after its lifetime has ended? There is no object.
  • 33. C++ Ground Rules : Lifetime Construction: An object is considered fully constructed when the control goes out of constructor. Destruction: C++ refuses to call destructors for objects that haven't been fully constructed When an object is destructed, all fully constructed sub-objects are destructed. Finalization: Destructors for all local objects are called on exit (except for abort(), exit() and longjmp()).
  • 34. Anatomy of a Function Safe Operations Operations with built-in types Compiler Mechanisms Call, Return, Try, Throw, Catch Safe Functions Unsafe Operations Functions Construction Copy Construction Copy Assignment Destruction operator new / delete … class A { }; A Viscera( A x , // Argument Copy A& rx , A* px ) { // Local objects A a ; A& ra = *px ; A* pa = new A(rx) ; try { // ... // Parameter Copy A a = // Return Value Copy Viscera( a , *pa , &ra ); // ... } catch ( A& e ) { // Handler } // Exception Destructor Thunk // Exception Object Copy throw x ; // Exception Exit // Temporary Object Copy return a ; // Normal Exit } // Local Object Cleanup
  • 35. Exceptional Design Rules Meyers’ Recommendations on Basic Exception Safety
  • 36. Exception Safety : Meyers Guidelines Item 9:  Use destructors to prevent resource leaks   Item 10:  Prevent resource leaks in constructors   Item 11:  Prevent exceptions from leaving destructors   Item 12:  Understand how throwing an exception differs from passing a parameter or calling a virtual function   Item 13:  Catch exceptions by reference   Item 14:  Use exception specifications judiciously   Item 15:  Understand the costs of exception handling  
  • 37. Meyers [9] : Use destructors to prevent resource leaks Situation A hierarchy of Polygonal objects Two methods: Poly* readPoly(istream&) Read from input stream, and Create (through factory). virtual void plotPoly() Object drawn on the plotter device Poly Quad Tri
  • 38. Meyers [9] : Use destructors to prevent resource leaks Classes class Poly { public: virtual void plotPoly() = 0; ... }; class Quad: public Poly { public: virtual void plotPoly(); ... }; class Tri: public Poly { public: virtual void plotPoly(); ... };
  • 39. Meyers [9] : Use destructors to prevent resource leaks plot() for the Graphic Device (unsafe) void plot(istream& myStream) { // while there's data while (myStream) { // get next poly Poly *pPoly = readPoly(myStream); // Plot the polygon pPoly->plotPoly(); // delete object that // readPoly returned delete pPoly; } } plotPoly() throws  *pPoly leaks
  • 40. Meyers [9] : Use destructors to prevent resource leaks plot() for the Graphic Device (safe) void plot(istream& myStream) { // while there's data while (myStream) { // get next poly Poly *pPoly = readPoly(myStream); try { // Plot the polygon pPoly->plotPoly(); } catch (...) { // delete object - exception delete pPoly; throw; // passes on exception } // delete object – no exception delete pPoly; } } Code Duplication
  • 41. Meyers [9] : Use destructors to prevent resource leaks Litter code with try and catch blocks. Duplicate cleanup code Normal paths and Exceptional paths. Executes anyway! Move the cleanup code that must always be executed into the destructor for an object local to plot(). Local objects are always destroyed when leaving a function, regardless of how that function is exited. The solution is to replace the pointer with an object that acts like a pointer aka, Smart Pointer
  • 42. Meyers [9] : Use destructors to prevent resource leaks Smart pointer Is a C++ object Stores pointers to dynamically allocated (heap / free store) objects Improves raw pointers by implementing Construction & Destruction Copying & Assignment Dereferencing: operator–> operator* Grossly mimics raw pointer syntax & semantics
  • 43. Meyers [9] : Use destructors to prevent resource leaks auto_ptr template<class T> class auto_ptr { public: // save ptr to object auto_ptr(T *p = 0): ptr_(p) {} // delete ptr to object ~auto_ptr() { delete ptr_; } // Indirection T* operator->() const { return ptr_; } ... private: // raw ptr to object T *ptr_; };
  • 44. Meyers [9] : Use destructors to prevent resource leaks plot() for the Graphic Device (safe) void plot(istream& myStream) { // while there's data while (myStream) { // get next poly auto_ptr<Poly> pPoly(readPoly(myStream)); // Plot the polygon pPoly->plotPoly(); } } pPoly->plotPoly(); means (pPoly.operator->())->plotPoly();
  • 45. Meyers [9] : Use destructors to prevent resource leaks Smart Pointers work as Holders of Resources RAII – Resource Acquisition is Initialization Idiom Scoped Acquisition – Release Paradigm Acquires / Locks in Constructor Releases / Unlocks in Destructor Ensures safety on face of exceptions
  • 46. Meyers [9] : Use destructors to prevent resource leaks Window Handling in Windows OS (unsafe) // This function leaks resources // if an exception is thrown void Display(const Information& info) { HANDLE w = CreateWindow( /* Creation Parameters */ ); /* Data preparations */ RenderWindow(w, info, /* Display Parameters */); /* Data Cleanup */ DestroyWindow(w); }
  • 47. Meyers [9] : Use destructors to prevent resource leaks Window Holder // class for Holding (acquiring and // releasing) a window handle class WindowHolder { public: WindowHolder(HANDLE h): w_(h) {} ~WindowHolder() { DestroyWindow(w_); } operator HANDLE() { return w_; } private: HANDLE w_; // Stop free functions being available WindowHolder(const WindowHolder&); WindowHolder& operator=(const WindowHolder&); };
  • 48. Meyers [9] : Use destructors to prevent resource leaks Window Handling in Windows OS (safe) // This function cleans up resources - always void Display(const Information& info) { WindowHolder w(CreateWindow( /* Creation Parameters */ )); /* Data preparations */ // WindowHandle is implicitly converted to HANDLE RenderWindow(w, info, /* Display Parameters */); /* Data Cleanup */ }
  • 49. Meyers [9] : Use destructors to prevent resource leaks Morale Resources should be encapsulated inside objects. Usually avoids resource leaks in the face of exceptions.
  • 50. More Questions What happens if an exception is thrown in the process of acquiring a resource, that is, in the constructor of a resource-acquiring class? What happens if an exception is thrown during the automatic destruction of such resources?
  • 51. Meyers [10] : Prevent resource leaks in constructors Consider:  class T { ... }; class T1 { public: T1(const T&); ... }; class T2 { public: T2(const T&); ... }; class A { public: A(const T&, const T& = (T)0, const T& = (T)0); ~A(); void f(const T&); ... private: T m_; T1 *p1_; T2 *p2_; };
  • 52. Meyers [10] : Prevent resource leaks in constructors Constructor (unsafe) / Destructor:  A::A(const T& d, const T& s1, const T& s2): m_(d), p1_(0), p2_(0) { if (s1 != (T)0) p1_ = new T1(s1); // 1 if (s2 != (T)0) p2_ = new T2(s2); // 2 } A::~A() { delete p1_; delete p2_’ }
  • 53. Meyers [10] : Prevent resource leaks in constructors Exception in body: operator (T) may throw. T::operator != may throw T::operator new may throw bad_alloc Constructor for T1 or T2 may throw Exception at Line 1 is safe.  m_ gets destructed. Exception at Line 2 leaks p1_ .  A::~A() does not get called as the object is not there. A::A(const T& d, const T& s1, const T& s2):m_(d), p1_(0), p2_(0) { if (s1 != (T)0) p1_ = new T1(s1); // Line 1 if (s2 != (T)0) p2_ = new T2(s2); // Line 2 }
  • 54. Meyers [10] : Prevent resource leaks in constructors Try Exception Fix by Dynamic Allocation Doesn’t work as pA is never assigned if the following throws T::operator new Constructor for A { A *pA = 0; try { pA = new A(d, s1, s2); ... } catch (...) { // catch all exceptions delete pA; // delete pA on an exception throw; // Rethrow exception } delete pA; // delete pA normally }
  • 55. Meyers [10] : Prevent resource leaks in constructors Constructor (safe) cleans up itself A::A(const T& d, const T& s1, const T& s2): m_(d), p1_(0), p2_(0) { try { if (s1 != (T)0) p1_ = new T1(s1); // 1 if (s2 != (T)0) p2_ = new T2(s2); // 2 } catch (...) { delete p1_; delete p2_; throw; } } A::~A() { delete p1_; delete p2_’ }
  • 56. Meyers [10] : Prevent resource leaks in constructors Constructor (safe): w/o code duplication A::A(const T& d, const T& s1, const T& s2): m_(d), p1_(0), p2_(0) { try { if (s1 != (T)0) p1_ = new T1(s1); // 1 if (s2 != (T)0) p2_ = new T2(s2); // 2 } catch (...) { CleanUp(); throw; } } A::~A() { CleanUp(); } A::CleanUp() { delete p1_; delete p2_; }
  • 57. Meyers [10] : Prevent resource leaks in constructors Reconsider:  class T { ... }; class T1 { public: T1(const T&); ... }; class T2 { public: T2(const T&); ... }; class A { public: A(const T&, const T& = (T)0, const T& = (T)0); ~A(); void f(const T&); ... private: T m_; T1 * const p1_; T2 * const p2_; };
  • 58. Meyers [10] : Prevent resource leaks in constructors Constructor (unsafe):  Exception at Line 1 is safe.  m_ gets destructed. Exception at Line 2 leaks p1_ .  A::~A() does not get called. No try-catch on Initializer list – only expressions. A::A(const T& d, const T& s1, const T& s2): m_(d), p1_((s1 != (T)0)? new T1(s1): 0), // Line 1 p2_((s2 != (T)0)? new T2(s2): 0) // Line 2 { }
  • 59. Meyers [10] : Prevent resource leaks in constructors Constructor (safe):  T1* A::InitT1(const T&s) { if (s != (T)0) return new T1(s); else return (T1*)0; } T2* A::InitT2(const T&s) { try { if (s != (T)0) return new T2(s); else return (T2*)0; } catch (...) { delete p1_; throw; } } A::A(const T& d, const T& s1, const T& s2): m_(d), p1_(InitT1(s1)), p2_(InitT2(s2)) { }
  • 60. Meyers [10] : Prevent resource leaks in constructors A better design:  class T { ... }; class T1 { public: T1(const T&); ... }; class T2 { public: T2(const T&); ... }; class A { public: A(const T&, const T& = (T)0, const T& = (T)0); ~A(); void f(const T&); ... private: T m_; const auto_ptr<T1> p1_; const auto_ptr<T2> p2_; };
  • 61. Meyers [10] : Prevent resource leaks in constructors Constructor (safe by design):  Exception at Line 1 is safe.  m_ gets destructed. Exception at Line 2 is safe.  m_ & p1_ get destructed. // Constructor A::A(const T& d, const T& s1, const T& s2): m_(d), p1_((s1 != (T)0)? new T1(s1): 0), // Line 1 p2_((s2 != (T)0)? new T2(s2): 0) // Line 2 { } // Destructor A::~A() { }
  • 62. Meyers [10] : Prevent resource leaks in constructors Moral Replace pointer class members with their corresponding auto_ptr objects Fortifies constructors against resource leaks in the presence of exceptions, Eliminates the need to manually deallocate resources in destructors, and Allows const member pointers to be handled in the same graceful fashion as non-const pointers.
  • 63. Meyers [11] : Prevent exceptions from leaving destructors A destructor is called in two situations When an object is destroyed under “normal” conditions When it goes out of scope or Is explicitly deleted. When an object is destroyed by the exception-handling mechanism during the stack-unwinding part of “exception propagation”.
  • 64. Meyers [11] : Prevent exceptions from leaving destructors Recap If an exception is thrown when another exception is active, terminate() is called and the program immediately terminates. From within a destructor, there is no robust way to determine if an exception is active.
  • 65. Meyers [11] : Prevent exceptions from leaving destructors Consider class Session { public: Session(); ~Session(); ... private: static void logCreation(Session *); static void logDestruction(Session *); }; Session::~Session() { // Fatal to throw here logDestruction(this); };
  • 66. Meyers [11] : Prevent exceptions from leaving destructors Manage the exceptions Session::~Session() { try { logDestruction(this); } catch (...) { // Fatal again if operator<<() throws cerr << &quot;Unable to log destruction of Session object&quot; << &quot;at address &quot; << this << &quot;.\n&quot;; } };
  • 67. Meyers [11] : Prevent exceptions from leaving destructors Bite the dust – swallow the exceptions Session::~Session() { try { logDestruction(this); } catch (...) { } };
  • 68. Meyers [11] : Prevent exceptions from leaving destructors Moral Keep exceptions from propagating out of destructors. Prevents terminate from being called during the stack-unwinding part of exception propagation. Helps ensure that destructors always accomplish everything they are supposed to accomplish.
  • 69. Meyers [12] : Throwing an exception differs from passing a parameter or calling a virtual function Control does not return to the throw site. Throw always copies the object. Catch needs to clean-up the thrown object. Parameter Matching is exact for Catch and done with the static type Overloaded Catch clauses are tried in lexical order.
  • 70. Meyers [13] : Catch exceptions by reference
  • 71. Meyers [14] : Use exception specifications judiciously
  • 72. Meyers [15] : Understand the costs of exception handling
  • 73. Handling Exceptions in C & C++ References & Credits
  • 74. References Handling Exceptions: Part 1 – 4 Robert Schmidt Modern C++ Design: Generic Programming & Design Pattern Applied Andrei Alexandrescu Exceptional C++ & More Exceptional C++ Herb Sutter Effective C++ & More Effective C++ Scott Meyers Standard Features Missing From VC++ 7.1. Part I: Exception Specifications Nemanja Trifunovic http://www.codeproject.com/cpp/stdexceptionspec.asp A Pragmatic Look at Exception Specifications http://www.gotw.ca/publications/mill22.htm

Editor's Notes

  • #9: We should outline the various Instrumentations needed for handling Function Calls depending on the kind of exception handling being supported: Normal Flow return Exceptional Flow with Stack Cutting setjmp / longjmp Exceptional Flow with Stack Unwinding try-catch-throw Naturally, keeping with the code separation / code organization motivations in mind, we do not need to refer to any of the local (goto’s) or global (errno / exit() etc) options here. We need to highlight, as we move from #1 to #3, how we are doing in terms of the basic issues (objectives) we have started off with. This will be more a philosophical introduction.
  • #10: These are the items needed for the discussion on Instrumentation. We’ll elaborate them in the following slides. We need to collect information on: How the calling order for finalizers decided? In normal flow and in exceptional flow. What exactly does the EH Handler do to achieve stack unwinding? How a sample EH Frame is laid out.
  • #11: We discuss the stack frame structure here. Function parameters Function return address Frame pointer Local Objects Callee save registers We’ll take a small example and show the stack frame on x86. Good resource is: http://www.unixwiz.net/techtips/win32-callconv-asm.html
  • #12: We discuss the context of a call here. Register PC / Return Address (eip on x86) Register SP / Stack Pointer (esp on x86) Register FP / Frame Pointer or Base Pointer (ebp on x86) With respect to the example, we’ll show the context on x86. Good resources is: http://www.unixwiz.net/techtips/win32-callconv-asm.html
  • #13: We discuss the finalization of a call here. How are the right destructors called in the right order? This is tricky once the function has a multiple return statements before / after a number of local object constructions. We can frame a small example and illustrate.
  • #14: We outline the normal flow in a function call: Caller prepares the Parameters Caller calls the Callee Callee saves the Context (Function Prologue) Callee does the job Callee restores the Context (Function Epilogue) Callee returns Caller cleans up the Parameters Caller uses the return value We can use the stack frame example for illustration. Good resource is: http://www.unixwiz.net/techtips/win32-callconv-asm.html
  • #15: We discuss the enhanced stack frame structure with (bold item). Function parameters Function return address Frame pointer Exception Handler frame Local Objects Callee save registers
  • #16: We need to discuss how EH Frame is maintained. Need more information on this. A good resource is: http://www.osronline.com/custom.cfm?name=articlePrint.cfm&amp;id=469
  • #17: This is the case of handling in C for setjmp / longjmp. Our discussion should follow as: Recap of the setjmp / longjmp with an example. Explanation of the jmp_buf structure for x86-32. This is from the setjmp.h header. With reference to stack frame and context, we need to explain how the information set for the buffer has been chosen. Explanation of the behavior of setjmp – low level steps. Assembly code of setjmp can says that. Explanation of the behavior of longjmp – low level steps. Assembly code of longjmp can says that. Justify why this is ‘stack cutting’ – that is finalizers are not invoked. We use the above example to illustrate. Good resource is: CS360 Lecture notes – Setjmp : http://www.cs.utk.edu/~plank/plank/classes/cs360/360/notes/Setjmp/lecture.html
  • #18: This is the case of handling in C for setjmp / longjmp. Our discussion should follow as: Recap of the setjmp / longjmp with an example. Explanation of the jmp_buf structure for x86-32. This is from the setjmp.h header. With reference to stack frame and context, we need to explain how the information set for the buffer has been chosen. Explanation of the behavior of setjmp – low level steps. Assembly code of setjmp can says that. Explanation of the behavior of longjmp – low level steps. Assembly code of longjmp can says that. Justify why this is ‘stack cutting’ – that is finalizers are not invoked. We use the above example to illustrate. Good resource is: CS360 Lecture notes – Setjmp : http://www.cs.utk.edu/~plank/plank/classes/cs360/360/notes/Setjmp/lecture.html
  • #19: We discuss the additional information that a stack frame structure may need to keep for C++ exceptions. We need to identify them beyond the following. Function parameters Function return address Frame pointer Exception Handler frame Local Objects Callee save registers
  • #20: What is a thunk? The word thunk has two meanings in computer science: a delayed computation (as in functional programming) a mapping of machine data from one system-specific form to another, usually for compatibility reasons. For example, running a 16-bit program on a 32-bit operating system may require a thunk from 16-bit addresses to 32-bit. Thunk in this sense may also refer to mappings from one calling convention to another or from one version of a library to another. This meaning is similar to the first—the &amp;quot;delayed computation&amp;quot; can be thought of as the &amp;quot;update&amp;quot; from the old format to the new. http://en.wikipedia.org/wiki/Thunk Why do we need a destructor thunk for the Exception object? How is it used? Good resource is: Intel presentation on: “C++ Exception Handling for IA-64 Unix”
  • #21: We need to discuss how the EH hook is maintained.
  • #22: This is the case of handling in C++ for try-catch-throw. Our discussion should follow as: Recap of the try-catch-throw with an example. It will be good to use the same example as setjmp / longjmp case. Introduce the basic notions of stack unwinding: Creation of Exception object Placement of destructor thunk for Exception object Wrapping up of the stack frame. Calling of Finalizers Matching for Handler (catch handlers are statically overloaded but dynamically dispatched). Explain why this will need RTTI. Invocation of the right handler. Exit from the handler Invocation of the thunk if no rethrow has been done. Flow / flowchart of the unwind logic. Role of the C++ Runtime system. Outline the data structures required. Stack Frame – modified RUNTIME_FUNCTION UNWIND_INFO TRY_REGION_TABLE CLEANUP_TABLE We use the example to illustrate. Good resources are: Intel presentation on: “C++ Exception Handling for IA-64 Unix” Exceptional Behavior - x64 Structured Exception Handling: http://www.osronline.com/custom.cfm?name=articlePrint.cfm&amp;id=469
  • #23: This is the case of handling in C++ for try-catch-throw. Our discussion should follow as: Recap of the try-catch-throw with an example. It will be good to use the same example as setjmp / longjmp case. Introduce the basic notions of stack unwinding: Creation of Exception object Placement of destructor thunk for Exception object Wrapping up of the stack frame. Calling of Finalizers Matching for Handler (catch handlers are statically overloaded but dynamically dispatched). Explain why this will need RTTI. Invocation of the right handler. Exit from the handler Invocation of the thunk if no rethrow has been done. Flow / flowchart of the unwind logic. Role of the C++ Runtime system. Outline the data structures required. Stack Frame – modified RUNTIME_FUNCTION UNWIND_INFO TRY_REGION_TABLE CLEANUP_TABLE We use the example to illustrate. Good resources are: Intel presentation on: “C++ Exception Handling for IA-64 Unix” Exceptional Behavior - x64 Structured Exception Handling: http://www.osronline.com/custom.cfm?name=articlePrint.cfm&amp;id=469
  • #24: This is the case of handling in C++ for try-catch-throw. Our discussion should follow as: Recap of the try-catch-throw with an example. It will be good to use the same example as setjmp / longjmp case. Introduce the basic notions of stack unwinding: Creation of Exception object Placement of destructor thunk for Exception object Wrapping up of the stack frame. Calling of Finalizers Matching for Handler (catch handlers are statically overloaded but dynamically dispatched). Explain why this will need RTTI. Invocation of the right handler. Exit from the handler Invocation of the thunk if no rethrow has been done. Flow / flowchart of the unwind logic. Role of the C++ Runtime system. Outline the data structures required. Stack Frame – modified RUNTIME_FUNCTION UNWIND_INFO TRY_REGION_TABLE CLEANUP_TABLE We use the example to illustrate. Good resources are: Intel presentation on: “C++ Exception Handling for IA-64 Unix” Exceptional Behavior - x64 Structured Exception Handling: http://www.osronline.com/custom.cfm?name=articlePrint.cfm&amp;id=469
  • #25: Nothing in life comes for free. While Exception support in C++ makes life much easier for the designer, coder and debugger; it makes life tough for the compiler writer. The main two costs are: Overhead during a non-exception flow Loss of Optimization options for the compiler. Good resource is: How much does Exception Handling cost, really? : http://www.nwcpp.org/Downloads/2006/ehc.ppt From this presentation, we can lift a couple of slides (we’ll exclude all references to SEH).