1 today’s objectives announcements homework #5 is due today. since this date is so close to the...

31
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

Upload: roger-barber

Post on 21-Jan-2016

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 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

1

Today’s ObjectivesToday’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-200624-Jul-2006

Page 2: 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

2

Review Quiz #4Review Quiz #4

Page 3: 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

3

6. Instantiate an objectfrom a class template

6. Instantiate an objectfrom a class template

List<Customer> customers;

Review Quiz #4Review 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.

Page 4: 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

4

Exception HandlingException Handling

Chapter 16

Page 5: 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

5

RobustnessRobustness

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)Exception Handling (Deitel, 811; Goodrich, 63)

Page 6: 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

6

ExceptionsExceptions

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)Exception Handling (Deitel, 811)

Page 7: 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

7

C++ Exception ObjectsC++ 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

<exception> 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)Exception Handling (Deitel, 811, 832)

Page 8: 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

8

C++ Exception HandlingC++ 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)Exception Handling (Deitel, 811)

Page 9: 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

9

Try-Catch BlockTry-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)Exception Handling (Deitel, 815)

Page 10: 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

10

Try-Catch ExampleTry-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 HandlingException 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.

Page 11: 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

11

Try-Catch ExampleTry-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 HandlingException 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";

}

Page 12: 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

12

Try-Catch ExampleTry-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 HandlingException 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.

Page 13: 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

13

Try-Catch ExampleTry-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 HandlingException 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.

Page 14: 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

14

Throwing an ExceptionThrowing 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 exceptionvoid 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)Exception Handling (Deitel, 818)

Page 15: 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

15

Re-throwing an ExceptionRe-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)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.

Page 16: 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

16

Catching Types of ExceptionCatching 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)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.

Page 17: 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

17

Throwing Other Data TypesThrowing 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)Exception Handling (C++ Language Reference)

Page 18: 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

18

Stack UnwindingStack 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)Exception Handling (Deitel, 823)

Page 19: 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

19

Memory RecoveryMemory 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)Exception Handling (C++ Language Reference)

Page 20: 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

20

TerminateTerminate

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)Exception Handling (C++ Language Reference)

Page 21: 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

21

Exception SpecificationException 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

Examplevoid 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)Exception Handling (Deitel, 821)

Page 22: 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

22

Exception SpecificationException 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 HandlingException Handling

Page 23: 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

23

Defining Your Own ExceptionDefining Your Own Exception

#ifndef LISTFULLEXCEPTION_H#define LISTFULLEXCEPTION_H

#include <exception>#include <string>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)Exception Handling (Josuttis, 25–31)

Page 24: 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

24

Performance PenaltyPerformance 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)Exception Handling (C++ Language Reference)

Page 25: 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

25

Using Exceptions in the DemoLibrary

Using Exceptions in the DemoLibrary

Page 26: 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

26

UML Sequence DiagramShowing the interaction in the DemoLibrary program

UML Sequence DiagramShowing 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

ExceptionsExceptions

Page 27: 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

27

UML Sequence DiagramShowing the interaction in the DemoLibrary program

UML Sequence DiagramShowing 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

ExceptionsExceptions

First, we change push_back so that it throws an exception when the array data member of its object is full

Page 28: 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

28

UML Sequence DiagramShowing the interaction in the DemoLibrary program

UML Sequence DiagramShowing 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

ExceptionsExceptions

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

Page 29: 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

29

UML Sequence DiagramShowing the interaction in the DemoLibrary program

UML Sequence DiagramShowing 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

ExceptionsExceptions

We make addLibraryItem re-throw the exception if it’s caught

Page 30: 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

30

UML Sequence DiagramShowing the interaction in the DemoLibrary program

UML Sequence DiagramShowing 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

ExceptionsExceptions

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

Page 31: 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

31

ReferencesReferences

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.