Professional Documents
Culture Documents
C++ Function Templates C++ Class Templates Exception and Exception Handler
Approaches for functions that implement identical tasks for different data types
Nave Approach
create unique functions with unique names for each combination of data types
Example
void PrintInt( int n ) { cout << "***Debug" << endl; cout << "Value is " << n << endl; } void PrintChar( char ch ) { cout << "***Debug" << endl; cout << "Value is " << ch << endl; } void PrintFloat( float x ) To output the traced values, we insert: { PrintInt(sum); } void PrintDouble( double d ) PrintChar(initial); { PrintFloat(angle); }
The use of the same name for different C++ functions, distinguished from each other by their parameter lists
Eliminates need to come up with many different names for identical tasks. Reduces the chance of unexpected results caused by using the wrong function name.
void Print( SomeType val ) { cout << "***Debug" << endl; cout << "Value is " << val << endl; }
Template argument
When the compiler instantiates a template, it substitutes the template argument for the template parameter throughout the function template.
Template Functions One Function Definition (a function template) Compiler Generates Individual Functions
Class Template
A C++ language construct that allows the compiler to generate multiple versions of a class by allowing parameterized data types. Class Template Template < TemplateParamList > ClassDefinition TemplateParamDeclaration: placeholder class typeIdentifier typename variableIdentifier
Class template arguments must be explicit. The compiler generates distinct class types called template classes or generated classes. When instantiating a template, a compiler substitutes the template argument for the template parameter throughout the class template.
Substitution Example
class GList_int { public:
int
int
bool IsPresent( /* in */ ItemType item ) const; private: int length; ItemType data[MAX_LENGTH]; }; int int
length++;
}
Stack<int,128> mystack;
Exception
An exception is a unusual, often unpredictable event, detectable by software or hardware, that requires special processing occurring at runtime In C++, a variable or class object that represents an exceptional event.
Easy to see if proper error checking implemented Harder to read application itself and see how code works Makes clear, robust, fault-tolerant programs C++ removes error handling code from "main line" of program new not allocating memory Out of bounds array subscript Division by zero Invalid function parameters
Exception handling
Common failures
Deals with synchronous errors (i.E., Divide by zero) Does not deal with asynchronous errors - disk I/O completions, mouse clicks - use interrupt processing Used when system can recover from error Exception handler - recovery procedure Typically used when error dealt with in different place than where it occurred Useful when program cannot recover but must shut down cleanly
Easier to write error-processing code Specify what type of exceptions are to be caught
Techniques in this chapter apply for multithreaded OS as well (windows NT, OS/2, some UNIX)
Exception handling another way to return control from a function or block of code
Handling Exception
If without handling, Program crashes Falls into unknown state An exception handler is a section of program code that is designed to execute when a particular exception occurs Resolve the exception Lead to known state, such as exiting the program
Standard Exceptions
new
Exceptions Thrown by Standard Library Routines Exceptions Thrown by user code, using throw statement
Processing exceptional situations Processing exceptions for components that cannot handle them directly Processing exceptions for widely used components (libraries, classes, functions) that should not process their own exceptions Large projects that require uniform error processing
Object typically a character string (error message) or class object If exception handler exists, exception caught and handled Otherwise, program terminates
Format
Enclose code that may have an error in try block Follow with one or more catch blocks
If exception occurs and matches parameter in catch block, code in catch block executed If no exception thrown, exception handlers skipped and control resumes after catch blocks throw point - place where exception occurred
Exception caught by closest exception handler Control exits current try block and goes to catch handler (if it exists) Example (inside function definition)
if ( denominator == 0 )
throw DivideByZeroException(); Throws a dividebyzeroexception object
Example:
catch ( DivideByZeroException ex) { cout << "Exception occurred: " << ex.what() <<'\n' }
If found, control resumes after last catch block If several handlers match thrown object, first one found is executed
The catch parameter is a public base class of the thrown object The catch parameter is a base-class pointer/ reference type and the thrown object is a derived-class pointer/ reference type The catch handler is catch( ... ) Thrown const objects have const in the parameter type
Unreleased resources
Resources may have been allocated when exception thrown catch handler should delete space allocated by new and close any opened files
FormalParameter
DataType VariableName
Execution of try-catch
A statement throws an exception
Control moves directly to exception handler
Exception Handler
Function call
Normal return
A Solution
int Quotient(int numer, int denom ) { if (denom == 0) throw DivByZero(); // The numerator // The denominator
A Solution
// quotient.cpp -- Quotient program #include<iostream.h> #include <string.h> int Quotient( int, int ); class DivByZero {}; // Exception class while(cin) { try { cout << "Their quotient: " << Quotient(numer,denom) <<endl; } catch ( DivByZero )//exception handler { cout<<Denominator can't be 0"<< endl; } // read in numerator and denominator
int main()
{ int numer; // Numerator int denom; // Denominator //read in numerator and denominator
} return 0; }
Templates are mechanisms for generating functions and classes on type parameters. We can design a single class or function that operates on data of many types
function templates class templates
An exception is a unusual, often unpredictable event that requires special processing occurring at runtime
throw try-catch
Rethrowing exceptions
Used when an exception handler cannot process an exception Rethrow exception with the statement:
throw; No arguments If no exception thrown in first place, calls terminate
Handler can always rethrow exception, even if it performed some processing Rethrown exception detected by next enclosing try block
1 2 3 4 5 6 7 8 9
#include <exception>
10 using std::exception; 11 12 void throwException() 13 { 14 15 16 17 18 19 } catch( exception e ) // Throw an exception and immediately catch it. try { cout << "Function throwException\n"; throw exception();
1. Load header
// generate exception
20
21
22 23 24 25 26 } 27 }
throw;
31
32 33 34 35 36 37 38 39 40 41 42 } } }
throwException();
cout << "This should not print\n";
cout << "Program control continues after catch in main" << endl; return 0;
2. Function call
3. Output
Function throwException Exception handled in function throwException Exception handled in main Program control continues after catch in main
Example:
Function can throw listed exceptions or derived types If other type thrown, function unexpected called throw() (i.e., no throw list) states that function will not throw any exceptions In reality, function can still throw exceptions, but calls unexpected (more later) If no throw list specified, function can throw any exception
Function unexpected
Calls the function specified with set_unexpected Default: terminate Calls function specified with set_terminate Default: abort Prototypes in <exception> Take pointers to functions (i.E., Function name) Function must return void and take no arguments Returns pointer to last function called by terminate or unexpected
Function terminate
Uncaught Exception
Function-call stack unwound when exception thrown and not caught in a particular scope
Tries
block Function in which exception was not caught terminates Local variables destroyed Control returns to place where function was called If control returns to a try block, attempt made to catch exception Otherwise, further unwinds stack If exception not caught, terminate called
A constructor cannot return a value - how do we let the outside world know of an error?
Keep defective object and hope someone tests it Set some variable outside constructor
A thrown exception can tell outside world about a failed constructor catch handler must have a copy constructor for thrown object