Exceptions David Rabinowitz. March 3rd, 2004 Object Oriented Design Course 2 The Role of Exceptions Definition: a method succeeds if it terminates in.

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
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.
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.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Error Handling with Exceptions Concepts C and other earlier languages often had multiple error-handling schemes, and these were generally established.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
C++ Exception Handling
1 CSC241: Object Oriented Programming Lecture No 28.
Exceptions Amit Shabtay. March 3rd, 2004 Object Oriented Design Course 2 Covariance\Contravariance Reminder class Parent { void test (covar : Mammal,
. Plab – Tirgul 10 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
Design by Contract David Talby. Software Correctness When is a class correct? It ’ s a relative concept; what is required? But it ’ s the correct question:
Exceptions (Large parts of these copied from Ed Schonberg’s slides)
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
Plab – Tirgul 8 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
Design by Contract & Exceptions David Talby. Software Correctness When is a class correct? – It ’ s a relative concept; what is required? – But it ’ s.
Stacks, Queues, and Deques
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
1 Exceptions and error handling. 2 Java exception mechanism when an error or exceptional condition occurs, you throw an exception which is caught by an.
Object Oriented Programming
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
Exception Handling Basic -- from generic idea to Java.
Natalia Yastrebova What is Coverity? Each developer should answer to some very simple, yet difficult to answer questions: How do I find new.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Introduction to Exception Handling and Defensive Programming.
C++ Memory Overview 4 major memory segments Key differences from Java
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Dynamic Memory. We will follow different order from Course Book We will follow different order from Course Book First we will cover Sect The new.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
ANU COMP2110 Software Design in 2003 Lecture 10Slide 1 COMP2110 Software Design in 2004 Lecture 12 Documenting Detailed Design How to write down detailed.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
C++ 程序语言设计 Chapter 12: Dynamic Object Creation. Outline  Object creation process  Overloading new & delete.
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.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Today: –Two simple binding examples. –Function Hiding.
DBC NOTES. Design By Contract l A contract carries mutual obligations and benefits. l The client should only call a routine when the routine’s pre-condition.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
1 Exceptions When the Contract is Broken. 2 Definitions A routine call succeeds if it terminates its execution in a state satisfying its contract A routine.
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.
י"ח/תשרי/תשע"ח Design by Contract David Talby.
C ++ MULTIPLE CHOICE QUESTION
Exception Handling in C++
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
CS 2704 Object Oriented Software Design and Construction
Jim Fawcett CSE687 – Object Oriented Design Spring 2001
Exceptions David Rabinowitz.
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
This pointer, Dynamic memory allocation, Constructors and Destructor
EE422C Software Implementation II
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Objects Managing a Resource
Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.
SWE 619 Last modified Fall 2007 Saket Kaushik, Paul Ammann
Computer Science 340 Software Design & Testing
Exception Handling.
SPL – PS3 C++ Classes.
Presentation transcript:

Exceptions David Rabinowitz

March 3rd, 2004 Object Oriented Design Course 2 The Role of Exceptions Definition: a method succeeds if it terminates in a state satisfying its contract. It fails if it does not succeed. Definition: An exception is a runtime event that may cause a routine to fail. Exception cases An assertion violation (pre-, post-, invariant, loop) A hardware or operating system problem Intentional call to throw A failure in a method causes an exception in its caller

March 3rd, 2004 Object Oriented Design Course 3 Disciplined Exception Handling Mistake 1: Handler doesn’t restore stable state Mistake 2: Handler silently fails its own contract There are two correct approaches Resumption: Change conditions, and retry method Termination: Clean up and fail (re-throw exception) Correctness of a catch clause Resumption: { True } Catch { Inv  Pre } Termination: { True } Catch { Inv }

March 3rd, 2004 Object Oriented Design Course 4 Improper Flow of Control Mistake 3: Using exceptions for control flow try { value = hashtable.find(key); } catch ( NotFoundException e ) { value = null; } It’s bad design The contract should never include exceptions It’s extremely inefficient Global per-class data is initialized and stored Each try, catch, or exception specification cost time Throwing an exception is orders of magnitude slower than returning from a function call

March 3rd, 2004 Object Oriented Design Course 5 Constructors & Destructors Never let an exception leave a destructor In C++: Throwing an exception while destroying due to another exception causes terminate() In finalize(): The finalize() method is stopped The result is resource leaks (yes, in Java too) C++ doesn’t destroy partially built objects Throwing an exception in a constructor after resources were allocated leads to resource leaks Either split initialization to a method, or avoid pointers Use auto_ptr members instead of T* pointers for const members or members initialized in constructor

March 3rd, 2004 Object Oriented Design Course 6 Case Study: Genericity It’s very difficult to write generic, reusable classes that handle exceptions well Genericity requires considering exceptions from the template parameters as well Both default and copy constructors may throw Assignment and equality operators may throw In Java: constructors, equals() and clone() may throw See Tom Cargill paper’s Stack class code “Warm-up” bugs not related to exceptions: Copy, assignment do not set top in empty stacks Assignment does not protect against self-assignment

March 3rd, 2004 Object Oriented Design Course 7 Goals Exception Neutrality Exceptions raised from inner code (called functions or class T) are propagated well Weak Exception Safety Exceptions (either from class itself or from inner code) do not cause resource leaks Strong Exception Safety If a method terminates due to an exception, the object’s state remains unchanged

March 3rd, 2004 Object Oriented Design Course 8 Case Study: Restoring State Bug: Throwing OutOfMemory in push() top has already been incremented count(), push(), pop() can no longer be used Fix: restore top when throwing the exception Bug: Throwing OutOfMemoty in operator=() Old array is freed before new one allocated In x=y, x would be inconsistent after failure Fix: Allocate new array into a temporary first

March 3rd, 2004 Object Oriented Design Course 9 Case Study: Memory Leaks Bug: What if T.operator=() throws? It can happen: stack > See assignment in for loop of copy constructor If T throws here, no stack destructor is called The array allocated in the first line is leaked Bug: Same problem in push() Again, assignment in for loop may throw Only new_buffer points to allocated array In case of exception, this array will be leaked

March 3rd, 2004 Object Oriented Design Course 10 Case Study: More on State Bug: pop() ends with return v[top--]; This involves copying the returned object What if its copy constructor throws? top has already been decremented State of the stack has changed, and the client cannot retry to pop the same element

March 3rd, 2004 Object Oriented Design Course 11 Case Study: More on Memory Bug: operator=() assumes T constructs well First line: delete []v; Second line: v = new T[nelems = s.nelems]; If T’s default constructor throws, then v is undefined This can lead to double delete: { stack x, y; y = x; // exception thrown – y.v is deleted } // end of scope – y.v is re-deleted

March 3rd, 2004 Object Oriented Design Course 12 Case Study: Conclusions Paper’s title: “a false sense of security” Combining exceptions and genericity is extremely difficult – STL handles this Java has many of the same problems Constructors, equals(), hashCode(), clone(), toString() and other Object methods may throw In collections: add(), addAll(), removeAll(), retainAll(), hashCode(), etc. may throw The throws keyword is no help since without genericity, many classes work with Object or with other high-level interfaces

March 3rd, 2004 Object Oriented Design Course 13 Guidelines for Exceptions When propagating an exception, try to leave the object in the same state it had in method entry Make sure const functions are really const Perform exception-prone actions early Perform them through temporaries Watch for side effects in expression that might throw If you can’t leave the object in the same state, try to leave it in a stable state Either re-initialize it, or mark it internally as invalid Do not leave dangling pointers in the object – delete pointers and free resources through temporaries

March 3rd, 2004 Object Oriented Design Course 14 Guidelines for Exceptions II Avoid resource leaks In constructors, initialize raw pointers or resource handles to null first and initialize them inside a try..catch block in the constructor body Don’t throw exceptions from a destructor / finalize() Don’t catch any exceptions you don’t have to Rewrite functions to preserve state if possible push() {v_[top_] = element; top_++; } Use catch(…) to deal with propagating exceptions Restore state and re-throw exception

March 3rd, 2004 Object Oriented Design Course 15 Guidelines for Exceptions III Don’t hide exceptions from your clients Always re-throw an exception caught with catch(…) Throw a different exception only to add information Make sure one catch block doesn’t hide another Use exception hierarchies Define base exception classes for each library Don’t be afraid of a deep hierarchy Consider inheriting a standard exception Don’t get too paranoid

March 3rd, 2004 Object Oriented Design Course 16 Summary Software Correctness & Fault Tolerance Design by Contract When is a class correct? Speed, Testing, Reliability, Documentation, Reusability, Improving Prog. Languages Exceptions What happens when the contract is broken? Neutrality, Weak Safety, Strong Safety