Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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 email 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 2 Review Quiz #4

3 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 4 Exception Handling Chapter 16

5 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 25 Using Exceptions in the DemoLibrary

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


Download ppt "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."

Similar presentations


Ads by Google