chapter 17 templates and exceptions part 2
DESCRIPTION
Chapter 17 Templates and Exceptions Part 2. Dale/Weems/Headington. 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. - PowerPoint PPT PresentationTRANSCRIPT
-
Chapter 17
Templates and ExceptionsPart 2Dale/Weems/Headington
-
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.
-
The throw Statement Throw: to signal the fact that an exception has occurred; also called raise Throw Statement
throw Expression
-
Throw examples (1)throw 5;string str = Invalid customer age;throw str;class SalaryError{ };SalaryError sal;throw sal;
-
Throw examples (2)Use of anonymous (unnamed) objectclass SalaryError{};throw SalaryError();A wrong waythrow SalaryError;
-
The try-catch Statementtry Blockcatch (FormalParameter) Blockcatch (FormalParameter) BlockTryCatchStatementHow one part of the program catches and processes the exception that another part of the program throws.FormalParameterDataType [VariableName]
-
Example of a try-catch Statementtry{ // Statements that process personnel data and may throw // exceptions of type int, string, and SalaryError}catch ( int ){ // Statements to handle an int exception}catch ( string s ){
- try-catch Continuedcout
-
Execution of try-catch No statements throw an exception Statement following entire try-catch statementA statement throwsan exceptionException HandlerStatements to deal with exception are executedControl moves directly to exception handler
-
Selecting an Exception HandlerThe computer: matches data types of throw clause with the data types in the catch clauses Searches in a north-to-south order Selects first handler whose data type matches that of the thrown exception Ellipse parameters are a wild card and catch all. Place the catch all handler last.
-
Selecting an Exception HandlerWhat constitutes a match?Suppose an object of type T is thrown.A catch block that takes an argument of type C is a match if:T and C are the same type.C adds a reference qualifies (e.g. int can be caught by int&)C is a base class of publicly derived class T
Note: matching process more restrictive than for function calls. Ex: int cant be caught by float or char
-
More on Selecting Exception Handlers The parameters 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
-
An exampleclass SalaryError// Exception class{};class BadRange// Exception class{};if ( condition )throw SalaryError();if ( condition )throw BadRange();
-
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
-
Throwing an Exception to be Caught by the Calling Codevoid Func3(){ try { Func4(); } catch ( ErrType ) { } }
void Func4() { if ( error ) throw ErrType(); }
NormalreturnFunctioncallReturn fromthrown exception
-
No ErrType handler
ErrType handler
No ErrType handler
No ErrType handler
No ErrType handler
throw ErrType();
ImmediatereturnImmediatereturnImmediatereturnFunc1No ErrType handler
No ErrType handler
No ErrType handler
No ErrType handler
No ErrType handler
throw ErrType();
ImmediatereturnProgramterminatesimmediatelyFunc2Func3Func4mainmainImmediate returnFunction Func1 has a handler for ErrTypeNo function has a handler for ErrTypeFunc1Func2Func3Func4Passing an Exception up the Chain of Function Calls
-
Re-Throwing an ExceptionThe throw expression is optional.throw;Re-throwing an exception in C++ allows partial exception handling.
-
An example (1)void WriteToFile( parameters ){ // Open a file for outputtry{while ( condition ){DoSomething( arguments ); // May throw a BadData exception // Write to output file}}
-
An example (2)catch ( BadData ){// Write massage to output file and // close itthrow;// Re-throw the exception}// Continue processing// and close the output file}
-
A Solution// quotient.cpp -- Quotient program#include #include using namespace std;int Quotient( int, int );class DivByZero // Exception class{};int main(){ int numer; // Numerator int denom; // Denominator
- cout > numer >> denom; while (cin) { try { cout
-
int Quotient( /* in */ int numer, // The numerator /* in */ int denom ) // The denominator{ if (denom == 0) throw DivByZero(); return numer / denom;}
-
Standard Exceptions Exceptions Thrown by the Languagenew, dynamic_cast, typeid, exception specificationExceptions Thrown by Standard Library RoutinesFacilities inherited from the C languageFacilities designed specifically for C++
- Exception thrown by newfloat* arr;try{arr = new float[50000];}catch ( bad_alloc ){cout
-
C library routine set errnoSimulate 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();}
-
Exceptions thrown by C++ libraries (1)Exceptions thrown by string classesvoid SomeFunc( parameters ){string s1, s2;try{s2 = s1.substr(pos, len);// May throw out_of_range()s1 = s1 + s1 + s2;// May throw length_error()}
- Exceptions thrown by C++ libraries (2)Exceptions thrown by string classescatch ( out_of_range ){cout
-
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??}
-
The end of Chapter 17 Part 2