Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 18 C++ 3370 – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.

Similar presentations


Presentation on theme: "CHAPTER 18 C++ 3370 – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source."— Presentation transcript:

1 CHAPTER 18 C++ 3370 – C++ Section 1: Exceptions

2 Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source of error The source detects, the client handles No relentless checking of return values scattered throughout the code Saves CPU cycles if no errors occur End user errors are the “exception”, not the rule

3 Catching an Exception One or more handlers follow a try block considered in order of appearance An exception matches a handler if it is of a compatible type: Same type Derived type void* catches all pointers catch(…) catches anything Always place the most specific handlers first try { … } catch (Foo& x) {… } catch (Bar& x) {… } catch (…) {…}// “…” rarely used

4 Throwing an Exception The exception object travels back up the call chain Execution backtracks until a matching handler is found Something very useful happens along the way…

5 Stack Unwinding As execution backtracks to a matching exception handler, the runtime stack is “unwound” The destructors for all local objects execute “Deterministic destruction” …

6 #include using namespace std; void h() { Foo f3; throw string("h() has a problem”); } void g() { Foo f2; h(); cout << "doing g..." << endl; } void f() { Foo f1; g(); cout << "doing f..." << endl; } Suppose Foo deallocates resources in its destructor.

7 int main() { try { f(); } catch(const string& msg) { cerr << "Error: " << msg << endl; } cout << "back in main" << endl; } /* Output: Foo ~Foo Error: h() has a problem back in main */

8 A Curiosity The statement throw string( ) creates a temporary string object in its scope How is that object eventually “passed” and made available in the scope of the handler? it’s not a normal function call

9 Exceptions are Copied A copy of the exception object is made A global, temporary object, which is carried back up the stack Exception types must have an accessible copy constructor If you catch by value, another copy is made Therefore: always catch exceptions by reference!

10 How does all this really work? throw is conceptually like a function call The runtime exception-handling mechanism backtracks up the program stack (the “call chain”) Reading information placed there by each function activation If no matching handler is found in a function being visited, any local objects are destroyed and the search continues up the stack

11 Space Overhead Stats on next slide struct C { ~C(){}// Forces exception handling }; void g();// for all we know, g may throw void f() { C c;// Destructor must be called g(); }

12 Compiler Exception Support Microsoft Visual C++ 2010 (omit option -EH) 654 bytes vs. 1390 bytes g++ 4.5 (option: -fno-exceptions) 932 bytes vs. 1252 bytes

13 noexcept Declarations You can add noexcept to a function declaration void f() noexcept {…} The compiler can use that information for optimization no exception overhead is required for that function Make sure it really doesn’t fail! you may have to use try-catch locally

14 Uncaught Exceptions If no matching handler exists for an exception, the program terminates Actually, std::terminate( ) is called Which calls abort() You can override this behavior But you should still terminate the program Maybe log a message first, close connections, etc. Always try to avoid uncaught exceptions!

15 Resource Management When an exception occurs you want to guard against resource leaks Use “Resource Acquisition is Initialization” (RAII) allocate resource in a constructor deallocate in the destructor Example: iostreams the destructor closes the file no need for “finally”

16 RAII via Object Wrappers (To leverage stack unwinding) class File // (Pretend we don’t have iostreams) { FILE* f; public: File(const char* fname, const char* mode) { f = fopen(fname, mode);// allocate } ~File() { fclose(f);// deallocate puts("File closed"); } };

17 void f(const char* fname) { File x(fname,"r"); g(x.getFP());// may fail; no worries }

18 Smart Pointers and RAII See slides 53-56 in Lippman3.pptx (I inadvertently skipped them)

19 Standard Exceptions Two Conceptual Categories std::runtime_error For unforeseen errors std::logic_error For careless programmer errors Both declared in Both derive from std::exception Declared in

20 What’s Wrong Here? void StackOfInt::grow() { // (Fields are capacity and data) // Enlarge stack’s data store capacity += INCREMENT; int* newData = new int[capacity]; for (size_t i = 0; i < count; ++i) newData[i] = data[i]; delete [] data; data = newData; }

21 An Improvement void StackOfInt::grow() { // Allocate a larger data store size_t newCapacity = capacity + INCREMENT; int* newData = new int[newCapacity]; for (size_t i = 0; i < count; ++i) newData[i] = data[i]; // Update state only when "safe" to do so delete [] data; data = newData; capacity = newCapacity; }

22 Fundamental Principle of Exception Safety Separate operations that may fail (i.e., throw an exception) from those that change state in your data Only change state when no exceptions can occur Corollary: Do one thing at a time (cohesion) This is why std::stack ::pop( ) returns void The returned copy might throw during construction the original object would be lost!

23 Rules of Exception Safety If you can’t handle an exception, let it propagate up “Exception neutral” Leave your data in a consistent state Use RAII to allocate resources Only change your state with non-throwing ops An object should only own one resource Functions should perform only one logical operation Destructors should never throw


Download ppt "CHAPTER 18 C++ 3370 – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source."

Similar presentations


Ads by Google