Exceptions.

Slides:



Advertisements
Similar presentations
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Advertisements

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.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Object Oriented Programming Elhanan Borenstein Lecture #12 copyrights © Elhanan Borenstein.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
Object Oriented Programming
Exceptions Handling Exceptionally Sticky Problems.
Introduction to Exception Handling and Defensive Programming.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
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.
Exception Handling in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Eighth Lecture Exception Handling in Java
Memory Management.
Exceptions handling Try, catch blocks Throwing exceptions.
C ++ MULTIPLE CHOICE QUESTION
Exception handling.
Java Exceptions a quick review….
Exception Handling in C++
C++ Exceptions.
Exceptions Error Handling and Recovery
16 Exception Handling.
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
Exceptions David Rabinowitz.
Chapter 6 CS 3370 – C++ Functions.
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Handling Exceptionally Sticky Problems
Tirgul 13 Exceptions 1.
MIT AITI 2003 Lecture14 Exceptions
Object-Oriented Programming (OOP) Lecture No. 45
Java Programming Language
Why exception handling in C++?
Syntax, semantics, and pragmatics
CMSC 202 Lesson 21 Exceptions II.
Exceptions C++ Interlude 3
Chapter 14: Exception Handling
What/how do we care about a program?
Handling Exceptions.
Exception Handling Chapter 9.
Exceptions Handling the unexpected
Exceptions with Functions
Overview of Memory Layout in C++
Exception Handling Chapter 9 Edited by JJ.
Exception Handling In Text: Chapter 14.
Exceptions 2 CMSC 202.
Data Abstraction: The Walls
Advanced C++ Exception Handling
Programming in C# CHAPTER - 7
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Pointers Pointers point to memory locations
Exceptions handling Try, catch blocks Throwing exceptions.
Handling Exceptionally Sticky Problems
Chapter 11: Exception Handling
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Exception Handling.
ENERGY 211 / CME 211 Lecture 24 November 14, 2008.
Presentation transcript:

Exceptions

? Query What does printf( ) return? When was the last time you checked it? What is a good approach to error handling?

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

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” Example: C01/Cleanup.cpp

A Curiosity The statement throw Foo( ) creates a temporary Foo object in its scope How is that object eventually made available in the scope of the handler?

Exceptions are Copies A copy of the exception object is made Exception types must have an accessible copy constructor If you catch by value, another copy is made Therefore: always catch exceptions by reference! Never throw pointers. How will the user know if it needs to be deleted? Who owns it?

How does all this really work? throw is conceptually like a function call The “function called” is the handler it finally lands on Which takes the exception object as a “parameter” This runtime 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, local objects’ are destroyed and the search continues Continues until a matching handler is found, or terminate is called.

Space Overhead Stats on next slide struct C { ~C(){} }; void g(); // for all we know, g may throw void f() C c; // Destructor must be called g(); } If we hadn’t explicitly put a destructor in C, the compiler would have would have known that it didn’t need to generate code to destroy c, and there would have been no overhead.

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

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! Example: C01/Terminator.cpp

Resource Management When an exception occurs you want to guard against resource leaks Use RAII! Example: C01/Wrapped.cpp

Standard Exceptions Two Conceptual Categories std::runtime_error For unforeseen errors std::logic_error For careless programmer errors Both declared in <stdexcept> Both derive from std::exception Declared in <exception> Example: C01/StdExcept.cpp Derive our exceptions from these categories, directly or indirectly.

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 throw from those that change state Only change state when no exceptions can occur Corollary: Do one thing at a time (cohesion) This is why std::stack<T>::pop( ) returns void The returned copy might throw during construction the 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 www.boost.org/more/generic_exeption_safety.html