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

Slides:



Advertisements
Similar presentations
CSE 332: C++ memory management idioms C++ Memory Management Idioms Idioms are reusable design techniques in a language –We’ll look at 4 important ones.
Advertisements

Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
COMP 121 Week 5: Exceptions and Exception Handling.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Week 11 Exceptions.
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
CS Advanced C++ Exception Handling Topic #5.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
CSE333 SECTION 7. Template vs Generics C++ templates are similar to preprocessor macros A template will be “materialized” into multiple copies with T.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
Object Oriented Programming
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
CSE 332: C++ memory management idioms C++ Memory Management Idioms Idioms are reusable design techniques in a language –We’ll look at 4 important ones.
Exceptions Handling Exceptionally Sticky Problems.
Introduction to Exception Handling and Defensive Programming.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
C++ Memory Overview 4 major memory segments Key differences from Java
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
 Managing the heap  Resource acquisition is initialization (RAII)  Overriding operator new and delete  Class-based memory pools.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
HANDLING EXCEPTIONS Chapter 9. Outline  Learn about the limitations of traditional error-handling methods  Throw exceptions  Use try blocks  Catch.
CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
LECTURE LECTURE 14 Exception Handling Textbook p
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling How to handle the runtime errors.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Exceptions handling Try, catch blocks Throwing exceptions.
C ++ MULTIPLE CHOICE QUESTION
Exception handling.
Java Exceptions a quick review….
Exceptions Error Handling and Recovery
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
CMSC202 Computer Science II for Majors Lecture 16 – Exceptions
CS 2704 Object Oriented Software Design and Construction
Jim Fawcett CSE687 – Object Oriented Design Spring 2001
Overview 4 major memory segments Key differences from Java stack
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Handling Exceptionally Sticky Problems
Why exception handling in C++?
CMSC 202 Lesson 21 Exceptions II.
Overview 4 major memory segments Key differences from Java stack
Chapter 15 Pointers, Dynamic Data, and Reference Types
Exceptions with Functions
Overview of Memory Layout in C++
Advanced C++ Exception Handling
Exceptions 1 CMSC 202.
Exceptions handling Try, catch blocks Throwing exceptions.
Handling Exceptionally Sticky Problems
Exception Handling.
Exceptions.
ENERGY 211 / CME 211 Lecture 24 November 14, 2008.
CMSC 202 Lesson 20 Exceptions 1.
Presentation transcript:

CHAPTER 18 C – C++ Section 1: Exceptions

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

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

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…

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

#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.

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 */

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

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!

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

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(); }

Compiler Exception Support Microsoft Visual C (omit option -EH) 654 bytes vs bytes g (option: -fno-exceptions) 932 bytes vs bytes

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

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!

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”

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"); } };

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

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

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

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; }

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; }

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!

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