1 Today’s Objectives  Announcements Homework #5 is due today. Since this date is so close to the end of the semester, no late assignments will be accepted.

Slides:



Advertisements
Similar presentations
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
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.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
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.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
C++ Exception Handling
1 CSC241: Object Oriented Programming Lecture No 28.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
© 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.
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 Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
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.
Chapter 12: Exception Handling
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.
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.
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.
1 Today’s Objectives  Announcements The Final Exam will be on Monday, 31-Jul, at 6 p.m. – There is no alternate time and no makeup!  Intro to the Standard.
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 –
1 Today’s Objectives  Announcements Homework #2 is due next Monday, 26-Jun, at the beginning of class Midterm Exam is Monday, 26-Jun – over material in.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Today’s Objectives  Announcements Turn in Homework 4 Quiz 4 will be on Wednesday, July 19 – It will have questions about inheritance, polymorphism,
(13-1) Exception Handling in C++ D & D Chapter 17 Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
1 Today’s Objectives  Announcements Homework #3 is due on Monday, 10-Jul, however you can earn 10 bonus points for this HW if you turn it in on Wednesday,
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
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.
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
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.
Exception Handling How to handle the runtime errors.
EE4E. C++ Programming Lecture 6 Advanced Topics. Contents Introduction Introduction Exception handling in C++ Exception handling in C++  An object oriented.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Exception handling.
Exception Handling in C++
C++ Exceptions.
IS 0020 Program Design and Software Tools
16 Exception Handling.
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
Today’s Objectives 5-Jul-2006 Announcements
Why exception handling in C++?
EXCEPTION HANDLING.
Chapter 14: Exception Handling
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
CMSC 202 Exceptions.
Presentation transcript:

1 Today’s Objectives  Announcements Homework #5 is due today. Since this date is so close to the end of the semester, no late assignments will be accepted and will NOT be accepted! The Final Exam will be on Monday, 31-Jul, at 6 p.m. – There is no alternate time and no makeup!  Review Quiz #4  Exception Handling (Ch. 16) Exceptions Try-catch blocks Throwing an exception Rethrowing exceptions Exception specification Defining your own exception classes  Bonus Lab 9 – Exceptions 24-Jul-2006

2 Review Quiz #4

3 6. Instantiate an object from a class template List customers; Review Quiz #4 Name of the class The List object name Template parameter – type of data used in the class Using the object name “customers” write a statement to instantiate a List object that has the default capacity and can contain Customer objects.

4 Exception Handling Chapter 16

5 Robustness  An important design goal of software engineering  Capable of handling the unexpected  Capable of providing the correct response, even when the input is incorrect  Advantages Our programs are more fault-tolerant They won’t crash when there’s a problem They are safer Exception Handling (Deitel, 811; Goodrich, 63)

6 Exceptions  Unexpected problems that occur when the program is running Occur infrequently Affect the operation of the program  Examples Trying to access an array outside of its bounds Trying to delete an element from an empty list Trying to divide by zero Unable to allocate memory needed by the program Exception Handling (Deitel, 811)

7 C++ Exception Objects  C++ exception objects Allow exceptions to be handled so the program doesn’t crash and doesn’t behave in an undefined way – more robust code The program is written so that the code “throws” an exception in response to an unexpected event Then the exception is “caught” and an appropriate action can occur   runtime_error The class used for throwing runtime exceptions in your program When there’s a potential error, an exception object is instantiated and used in the exception-handling procedures Exception Handling (Deitel, 811, 832)

8 C++ Exception Handling Procedure for handling unexpected errors 1.Write functions so that they automatically detect a potential error condition such as adding another element to an array that’s already full 2.In the program, we “try” the function 3.If there is an error condition, the function will “throw” an exception as a signal to the calling program that something is wrong 4.Then the calling program will “catch” the exception, and it can take appropriate action Exception Handling (Deitel, 811)

9 Try-Catch Block  Used for exception handling  When a function might throw an exception, its call is placed inside a “try block” try{ //... }  If an exception is thrown by a function call inside the block, then program control goes to the next block after the try block, which must be a “catch block” catch( runtime_error &e ){ //... }  At that point, the program can take appropriate action Exception Handling (Deitel, 815)

10 Try-Catch Example If we write the “ push_back ” function so that it throws an exception whenever the array is full, then we can catch the exception like this: Exception Handling Call push_back in a try block. void addRentalItem( Movie& item ){ try{ rentalItems.push_back(item); } catch( runtime_error& e ){ cout << e.what() << endl; } cout << "Skipped catch"; } If everything works, the program skips the catch block.

11 Try-Catch Example If we write the “ push_back ” function so that it throws an exception whenever the array is full, then we can catch the exception like this: Exception Handling Call push_back in a try block. If push_back throws an exception, the exception object goes to the catch block. void addRentalItem( Movie& item ){ try{ rentalItems.push_back(item); } catch( runtime_error& e ){ cout << e.what() << endl; } cout << "Skipped catch"; }

12 Try-Catch Example If we write the “ push_back ” function so that it throws an exception whenever the array is full, then we can catch the exception like this: Exception Handling Call push_back in a try block. If push_back throws an exception, the exception object goes to the catch block. void addRentalItem( Movie& item ){ try{ rentalItems.push_back(item); } catch( runtime_error& e ){ cout << e.what() << endl; } cout << "Skipped catch"; } The catch block has a reference to the exception object as an argument.

13 Try-Catch Example If we write the “ push_back ” function so that it throws an exception whenever the array is full, then we can catch the exception like this: Exception Handling Call push_back in a try block. If push_back throws an exception, the exception object goes to the catch block. void addRentalItem( Movie& item ){ try{ rentalItems.push_back(item); } catch( runtime_error& e ){ cout << e.what() << endl; } cout << "Skipped catch"; } The catch block has a reference to the exception object as an argument. The what() method returns a message.

14 Throwing an Exception  When a member function detects a potential error, it can “throw an exception” Create an exception object Stop the function Return the exception object to the calling program – control goes to the calling program at the appropriate catch block  Example of a member function that throws an exception void push_back( Movie& item ){ if( sz < capacity ){ RentalItem *pItem = new Movie(item); myData[sz] = pItem; sz++; } else throw runtime_error("List is full"); } Exception Handling (Deitel, 818)

15 Re-throwing an Exception We might decide not to handle the exception in the first catch block. We can re-throw it to the next catch block like this: Exception Handling (Deitel, 818) void addRentalItem( Movie& item ){ try{ rentalItems.push_back(item); } catch( runtime_error& e ){ throw; } If push_back throws an exception, the exception object goes to the catch block, but then it is thrown again. At that point, it goes to the next catch block or to the code that called addRentalItem and looks for a catch block there.

16 Catching Types of Exception int main(){ Store myStore; Movie movie1("The Matrix",5,"Wachowski","1999"); try{ myStore.addRentalItem(movie1); } catch( runtime_error& e ){ cout << e.what(); } catch( exception ){ cout << "Trouble"; } catch(... ){ cout << "Unspecified error"; } Exception Handling (Josuttis, 562) A catch block will catch only the type of exception object that is specified by the parameter More general types can be specified in the next catch blocks, until the “catch-all” handler at the end.

17 Throwing Other Data Types  Other data types can be thrown, not just exception objects char *buffer; try{ buffer = new char[512]; if( buffer == 0 ) throw "Memory allocation failure!"; } catch( char * str ){ cout << "Exception raised: " << str << '\n'; } Exception Handling (C++ Language Reference)

18 Stack Unwinding  When an exception is thrown but not caught, the program attempts to catch it in the next outer catch block.  When a function throws an exception, all of its variables are removed from the stack and control goes to the function that called it.  If the calling function doesn’t catch the exception, it is also removed from the stack  This process is called “stack unwinding” and it continues until the exception is caught or the program terminates Exception Handling (Deitel, 823)

19 Memory Recovery  During stack unwinding, destructors are called for any local objects instantiated before the exception was thrown class CDtorDemo { public: CDtorDemo(){cout << "Constructing CDtorDemo.\n";} ~CDtorDemo(){cout << "Destructing CDtorDemo.\n";} }; void MyFunc() { CDtorDemo D; //Instantiate a local object in the function cout << "Throwing exception.\n"; throw runtime_error("Exception test."); } int main() { try { cout << "In try block, calling MyFunc().\n"; MyFunc(); } catch( runtime_error e ) { cout << "In catch handler.\n"; cout << "Caught exception: " << e.what() << "\n"; } cout << "Back in main. Execution resumes here.\n"; } Exception Handling (C++ Language Reference)

20 Terminate  Predefined function used with exception handling  If no handler catches an exception, terminate() is called  Its default action is to call abort()  In your program, you can tell terminate to call another function instead of abort Advantage – you can write a function that recovers resources before your program shuts down, and then call it with terminate The function that you write should call exit(), but if it doesn’t, then abort will be called Must have no arguments, and void as the return value set_terminate(Arnold); //called anywhere Exception Handling (C++ Language Reference)

21 Exception Specification  When writing a function that throws an exception, you can specify which exceptions the function can throw Called the “throw list” or “exception specification”  A function with no exception specification can throw any exception  Example void push_back( Movie& item ) throw( runtime_error ) { if( sz < capacity ){ RentalItem *pItem = new Movie(item); myData[sz] = pItem; sz++; } else throw runtime_error("List is full"); } Exception Handling (Deitel, 821)

22 Exception Specification  Unfortunately, MS Visual Studio.NET 2003 does not support exception specifications Will cause a warning Will not cause any error in your program  Use the following preprocessor directive to disable the MS Visual Studio warnings about their lack of support for the exception specification. #pragma warning( disable : 4290 ) Exception Handling

23 Defining Your Own Exception #ifndef LISTFULLEXCEPTION_H #define LISTFULLEXCEPTION_H #include using std::runtime_error; using std::string; class ListFullException : public runtime_error{ public: ListFullException(const string msg = "List Full") : runtime_error( msg ) { } ); #endif Exception Handling (Josuttis, 25–31)

24 Performance Penalty  Exception handling requires extra processing that may slow down your program  Exceptions should not be used to control the program’s normal flow  Exceptions should be used to signal unusual or unanticipated problems Exception Handling (C++ Language Reference)

25 Using Exceptions in the DemoLibrary

26 UML Sequence Diagram Showing the interaction in the DemoLibrary program book(“C++ How to Program",4) Library user myLibrary : Library myList : LibraryItemList book : Book *pItem : Book addLibraryItem(book) push_back(book) book new Book(book) pItem Exceptions

27 UML Sequence Diagram Showing the interaction in the DemoLibrary program book(“C++ How to Program",4) Library user myLibrary : Library myList : LibraryItemList book : Book *pItem : Book addLibraryItem(book) push_back(book) book new Book(book) pItem Exceptions First, we change push_back so that it throws an exception when the array data member of its object is full

28 UML Sequence Diagram Showing the interaction in the DemoLibrary program book(“C++ How to Program",4) Library user myLibrary : Library myList : LibraryItemList book : Book *pItem : Book addLibraryItem(book) push_back(book) book new Book(book) pItem Exceptions First, we change push_back so that it throws an exception when the array data member of its object is full Since push_back might throw an exception, it has to be inside a try block when it’s called in addLibraryItem

29 UML Sequence Diagram Showing the interaction in the DemoLibrary program book(“C++ How to Program",4) Library user myLibrary : Library myList : LibraryItemList book : Book *pItem : Book addLibraryItem(book) push_back(book) book new Book(book) pItem Exceptions We make addLibraryItem re-throw the exception if it’s caught

30 UML Sequence Diagram Showing the interaction in the DemoLibrary program book(“C++ How to Program",4) Library user myLibrary : Library myList : LibraryItemList book : Book *pItem : Book addLibraryItem(book) push_back(book) book new Book(book) pItem Exceptions We make addLibraryItem re-throw the exception if it’s caught Since we know that addLibraryItem might throw an exception, it always has to be called inside a try block

31 References Deitel, H. M., and P. J. Deitel, C++ How to Program, Fifth Edition. Upper Saddle River, NJ: Prentice Hall, Folk, M. J., B. Zoellick, G. Riccardi, File Structures, An Object-Oriented Approach with C++. Boston: Addison-Wesley, Goodrich, M. T., R. Tamassia, and D. Mount, Data Structures and Algorithms in C++. Hoboken, NJ: John Wiley & Sons, Inc., Lippman, Stanley B., and Josee Lajoie, C++ Primer. Boston: Addison- Wesley, 1998.