1 chapter 17-2 templates and exceptions dale/weems

29
1 Chapter 17-2 Templates and Exception s Dale/Weems

Upload: ivan-molden

Post on 16-Dec-2015

220 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

1

Chapter 17-2Templates

and Exceptions

Dale/Weems

Page 2: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

2

An Exception is…

An exception is an unusual, often unpredictable event, detectable by software or hardware, that requires special processing; also, in C++, a variable or class object that represents an exceptional event

An exception handler is a section of program code that is executed when a particular exception occurs

Page 3: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

3

The throw Statement

Throw: to signal the fact that an exception has occurred; also called raise

ThrowStatementthrow Expression

Page 4: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

4

Throw examples (1) throw 5; string str = “Invalid customer age”;

throw str; class SalaryError

{};

SalaryError sal;

throw sal;

Page 5: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

5

Throw examples (2) Use of anonymous (unnamed) object

class SalaryError

{};

throw SalaryError(); A wrong way

throw SalaryError;

Page 6: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

6

The try-catch Statement

try Blockcatch (FormalParameter) Blockcatch (FormalParameter)

TryCatchStatement

How one part of the program catches and processes the exception that another part of the program throws.

FormalParameter

DataType VariableName

Page 7: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

7

Example of a try-catch Statement

try

{

// Statements that process personnel data and may throw

// exceptions of type int, string, and SalaryError

}

catch (int)

{

// Statements to handle an int exception

}

Page 8: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

8

try-catch Continuedcatch (string s)

{

cout << s << endl; // Prints "Invalid customer age"

// More statements to handle an age error

}

catch (SalaryError)

{

// Statements to handle a salary error

}

Page 9: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

9

Execution of try-catch

No statements throw

an exception

Statement following entire try-catch

statement

A statement throws

an exception

Exception Handler

Statements to deal with exception are executed

Control moves directly to exception handler

Page 10: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

10

Selecting an Exception Handler

The computer

• Examines data types of the formal parameters in exception handlers

• Searches in a “north-to-south” order

• Selects first formal parameter whose data type matches that of the thrown exception

• Ellipse parameters are a “wild card” and catch all (Place the “catch all” handler last)

Page 11: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

11

More on Selecting Exception Handlers

• The parameter’s name is needed only if statements in the body of the exception handler use that variable

• It is a good idea to use only

user-defined classes (and structs) as exception types

one type per exception

descriptive identifiers

Page 12: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

12

An exampleclass SalaryError // Exception class{};class BadRange // Exception class{};…if ( condition )

throw SalaryError();…if ( condition )

throw BadRange();

Page 13: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

13

Nonlocal Exception Handlers

• It is more common for the throw to occur inside a function that is called from within a try-clause than for the throw to be located within the try-catch statement

Page 14: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

14

Throwing an Exception to be Caught by the Calling Code

void Func4() { if (error) throw ErrType(); }

Normalreturn

void Func3(){ try { Func4(); } catch (ErrType) { } }

Functioncall

Return fromthrown exception

Page 15: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

15

NoErrType handler

ErrType handler

NoErrTypehandler

NoErrTypehandler

No ErrType handler

throw ErrType();

Call

Call

Call

Call

Immediatereturn

Immediatereturn

Immediatereturn

Func1

No ErrType handler

No ErrType handler

No ErrType handler

No ErrType handler

No ErrType handler

throw ErrType();

Call

Call

Call

Call

Immediatereturn

Immediatereturn

Immediatereturn

Programterminatesimmediately

Func2

Func3

Func4

mainmain

Immediate return

Function Func1 has a handler for ErrType No function has a handler for ErrType

Func1

Func2

Func3

Func4

Passing an Exception up the Chain of Function Calls

Page 16: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

16

Re-Throwing an Exception

The throw expression is optionalthrow;

Re-throwing an exception in C++ allows partial exception handling

Page 17: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

17

An example (1)

void WriteToFile( parameters ){

… // Open a file for outputtry{

while ( condition ){

DoSomething( arguments ); // May throw a BadData exception… // Write to output file

}}

Page 18: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

18

An example (2)

catch ( BadData ){

… // Write massage to output file and // close it

throw; // Re-throw the exception}… // Continue processing

// and close the output file}

Page 19: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

19

Standard Exceptions

Exceptions Thrown by the Language new, dynamic_cast, typeid, exception specification

Exceptions Thrown by Standard Library Routines

Facilities inherited from the C language Facilities designed specifically for C++

Page 20: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

20

Exception thrown by newfloat* arr;try{

arr = new float[50000];}catch ( bad_alloc ){

cout << “*** Out of memory. Can’t allocate array.”<< endl;

return 1; // Terminate the program}… // Continue. Allocation succeeded

Page 21: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

21

C library routine set errno Simulate throwing exceptions from C library

routinesclass CLibErr // Our own exception class{};…void SomeFunc( parameters ){

…errno = 0;C_lib_routine( arguments );if (errno != 0)

throw CLibErr();…

}

Page 22: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

22

Exceptions thrown by C++ libraries (1) Exceptions thrown by string classes

void SomeFunc( parameters ){

string s1, s2;try{

…s2 = s1.substr(pos, len);

// May throw out_of_range()s1 = s1 + s1 + s2;

// May throw length_error()…

}

Page 23: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

23

Exceptions thrown by C++ libraries (2) Exceptions thrown by string classes

catch ( out_of_range ){

cout << “Exception: out_of_range in SomeFunc”<< endl;

throw; // Re-throw exception to a caller}catch ( length_error ){

cout << “Exception: length_error in SomeFunc”<< endl;

throw; // Re-throw exception to a caller}… // Continue if no errors

}

Page 24: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

24

Dividing by ZEROApply what you know:

int Quotient(/* in */ int numer, // The numerator

/* in */ int denom) // The denominator

{

if (denom != 0)

return numer / denom;

else

// What to do??

}

Page 25: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

25

A Solution// “quotient.cpp” -- Quotient program

#include<iostream>#include <string>

using namespace std;

int Quotient(int, int);

class DivByZero // Exception class

{};

int main()

{

int numer; // Numerator

int denom; // Denominator

cout << "Enter numerator and denominator: ";

Page 26: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

26

cin >> numer >> denom;

while (cin) { try { cout << "Their quotient: "

<< Quotient(numer, denom) << endl;

}

catch (DivByZero)

{

cout << "*** Denominator can't be 0"

<< endl;

}

cout << "Enter numerator and denominator: ";

cin >> numer >> denom; } return 0;}

Page 27: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

27

int Quotient(/* in */ int numer, // The numerator

/* in */ int denom) // The denominator

{

if (denom == 0)

throw DivByZero();

return numer / denom;

}

Page 28: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

28

Appointment Calendar

Replace array-based list with linked list to demonstrate that changing implementation doesn’t change client code

Add exceptions to Appointment Calendar Program

Page 29: 1 Chapter 17-2 Templates and Exceptions Dale/Weems

29

The End of Chapter 17 Part 2