Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 1 Exceptions exceptiona program.

Slides:



Advertisements
Similar presentations
1 Stacks Chapter 4. 2 Objectives You will be able to: Describe a stack as an ADT. Build a dynamic-array-based implementation of stacks. Build a linked-list.
Advertisements

Lecture 9. 2 Exception  An exception is a unusual, often unpredictable event, detectable by software or hardware, that requires special processing occurring.
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.
1 Chapter 17-2 Templates and Exceptions Dale/Weems.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
 2006 Pearson Education, Inc. All rights reserved. Exception Handling in C++ CS-2303, C-Term Exception Handling in C++ CS-2303 System Programming.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 23 - Exception Handling Outline 23.1Introduction 23.2When Exception Handling Should Be Used 23.3Other.
Index Exception handling Exception In Java Exception Types
CSIS 123A Lecture 11 Exception Handling. Introduction  Typical approach to development:  Write programs assuming things go as planned  Get ‘core’ working.
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.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Exception Handling: A Deeper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
Exceptions and Exception Handling Carl Alphonce CSE116.
C++ Exception Handling
1 CSC241: Object Oriented Programming Lecture No 28.
CS Advanced C++ Exception Handling Topic #5.
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:
Rossella Lau Lecture 9, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 9: Application with Exception Handling 
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
Introduction to C++ Templates and Exceptions l C++ Function Templates l C++ Class Templates l Exception and Exception Handler.
Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 13 - Exception Handling Outline 13.1Introduction 13.2When Exception Handling Should Be Used.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
1 CSC241: Object Oriented Programming Lecture No 27.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Exceptions and Program Correctness based on the original work by Dr. Roger deBry Version 1.1.
Exception Handling Fall 2008 Dr. David A. Gaitros
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 23 - Exception Handling Outline 23.1Introduction.
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.
Exception Handling Outline 23.1 Introduction
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
LECTURE LECTURE 14 Exception Handling Textbook p
1 Chapter 17 Templates and Exceptions Dale/Weems.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Exception Handling How to handle the runtime errors.
Composition OO Software Design and Construction Computer Science Dept Va Tech January 2000 ©2000 McQuain WD 1 Composition: Cooperating Classes Composition.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
EE4E. C++ Programming Lecture 6 Advanced Topics. Contents Introduction Introduction Exception handling in C++ Exception handling in C++  An object oriented.
Introduction to C++ Templates and Exceptions C++ Function Templates C++ Class Templates Exception and Exception Handler.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
1 Data Structures CSCI 132, Spring 2016 Notes_ 5 Stacks.
Exception handling.
Exception Handling in C++
IS 0020 Program Design and Software Tools
Exceptions Error Handling and Recovery
Exceptions Exceptions are used to signal that an unexpected event has happened in a program C++ will generate exceptions for some errors in the program.
Exceptions.
CS 2704 Object Oriented Software Design and Construction
Why exception handling in C++?
Chapter 14: Exception Handling
Advanced C++ Exception Handling
Exception Handling.
Presentation transcript:

Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 1 Exceptions exceptiona program error that occurs during execution, or a “signal” generated (“thrown”) when a program execution error is detected Exceptions may be thrown by hardware or software; we consider only the latter. If a software exception is thrown, and an exception-handler code segment is in effect for that exception, then flow of control is transferred to the handler. If there is no handler for the exception, the program will be terminated.

Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 2 Stack Unwinding If a function throws an exception, and does not catch it locally, then control is transferred to the calling function, which is now given an opportunity to catch the exception. When the exception is caught, the catch block is executed and then the catching function may resume execution. This process continues until either a function catches the exception or all calls have been unwound. In the latter case, the program is terminated. H() G() F() main() runtime stack

Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 3 Multi-Level Unwinding void createList(int* Array, int Size); int getUserInput( ); int main() { int* Array; int Dimension; try { createList(Array, Dimension); } catch (int e) { cerr << "Cannot allocate: " << e << endl; return; } catch (bad_alloc b) { cerr << "Allocation failed" << endl; return; } Exception thrown in a called function.

Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 4 Multi-Level Unwinding void createList(int*& Array, int Size) { Size = getUserInput(); try { Array = new int[Size]; } catch (bad_alloc b) { // you can catch an exception throw (b); // and re-throw it } int getUserInput( ) { int Response; cout << "Please enter the desired dimension“ << endl; cin >> Response; if (Response <= 0) { throw (Response); // caught in main() } return Response; }

Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 5 throw() specification int F( ); // F may throw an exception // of any type int G( ) throw( ); // G may not throw any // exception int H( ) throw( bad_alloc); // H may only throw an // exception of spec'd // type. The potential for a function to throw an exception may be explicitly shown by adding a throw specification to its declaration and implementation: Note:this is what the Standard says; what your compiler supports may be different.

Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 6 Thrown Value May Be an Object class BadDimension { }; int getUserInput( ) throw(BadDimension); void main() { int Value; try { Value = getUserInput(); } catch (BadDimension e) { cerr << "User is an idiot." << endl; return; } Thrown value is an object of a trivial class – this IS legal. In the simplest case, we may declare a trivial class simply to throw instances of it:

Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 7 Stack with Useful Exceptions class Stack { private: int Capacity; // stack array size int Top; // first available index string* Stk; // stack array public: Stack(int InitSize = 0) throw (StackException); bool Push(string toInsert) throw (StackException); string Pop() throw (StackException); bool isEmpty() const; bool isFull() const; ~Stack(); }; class StackException { private: string Msg; public: StackException(string M = "unspecified"); string getMessage() const; };

Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 8 Using Exceptions Exceptions are particularly useful in library code, such as generic data structures and algorithms. The library will throw an exception and allow the client code to catch it and deal with it in a problem-specific context. A thrown exception will only be caught if there is a catch block whose function is on the runtime stack and which is looking for an exception of the type that has been thrown. catch(…) will catch an exception of ANY type. Caught exceptions can be re-thrown if desired. Control does NOT return to the point where the exception was thrown.

Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 9 Stack with Exceptions Stack::Stack(int InitSize) throw (StackException) { if (InitSize <= 0) { Capacity = Top = 0; Stk = NULL; return; } Capacity = InitSize; Top = 0; Stk = new(nothrow) string[InitSize]; if (Stk == NULL) { throw (StackException("stack allocation failed")); } In the Stack constructor implementation, we can throw an object holding an appropriate message, if the initial allocation fails:

Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 10 Stack with Exceptions string Stack::Pop() throw (StackException) { if ( (Top > 0) && (Top < Capacity) ) { Top--; return Stk[Top]; } throw StackException("stack underflow"); return string(""); } In the Stack::Pop() implementation, we can throw an object holding an appropriate message, if the stack is empty:

Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 11 A Memory-management Exception bool Stack::Push(string toInsert) throw (StackException) { if (Top == Capacity) { string* tmpStk = new(nothrow) string[2*Capacity]; if (tmpStk == NULL) { throw StackException("stack overflow"); } for (int Idx = 0; Idx < Capacity; Idx++) { tmpStk[Idx] = Stk[Idx]; } delete [] Stk; Stk = tmpStk; Capacity = 2*Capacity; } Stk[Top] = toInsert; Top++; return true; } Here, we could just allow new to throw a bad_alloc exception, but the use of a custom message simplifies the interface and the catch logic…

Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 12 Driver int main() { const int Size = 10; Stack s1(Size); s1.Push("First"); s1.Push("Second"); s1.Push("Third"); s1.Push("Fourth"); for (int Idx = 0; Idx < Size; Idx++ ) { try { s1.Pop(); } catch (StackException e) { cout << "Error: " << e.getMessage() << endl; cout << " occurred calling s1.Pop() in main()" << " with index " << Idx << endl; return 1; } return 0; }

Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 13 Conclusions Do not view exceptions as simply another control mechanism — the cost of a throw/catch action is too high and the alteration of flow control is too difficult to understand. (It has the potential to be almost as bad as a goto.) Design your exceptions to provide useful information; every thrown exception needs to be chased back to a generating error, so it's useful to know exactly where the exception was thrown, triggering values of local variables and/or parameters, etc. It is very common to design a hierarchy of exception classes, using inheritance. We will examine that later…