Post on 02-Apr-2018
7/27/2019 OOPs Unit-III
1/47
Introduction to
C++ Templates and Exceptions
C++ Function Templates
C++ Class Templates
Exception and Exception Handler
7/27/2019 OOPs Unit-III
2/47
C++ Function Templates
Approaches for functions that implement
identical tasks for different data types
Nave Approach
Function Overloading
Function Template
Instantiating a Function Templates
7/27/2019 OOPs Unit-III
3/47
Approach 1: Nave Approach create unique functions with unique
names for each combination of data
types
difficult to keeping track of multiple
function names lead to programming errors
7/27/2019 OOPs Unit-III
4/47
Examplevoid PrintInt( int n )
{cout
7/27/2019 OOPs Unit-III
5/47
Approach 2:Function Overloading
(Review) 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 resultscaused by using the wrong function name.
7/27/2019 OOPs Unit-III
6/47
7/27/2019 OOPs Unit-III
7/47
Approach 3: Function Template
A C++ language construct that allows the compilerto generate multiple versions of a function by
allowing parameterized data types.
Template < TemplateParamList >
FunctionDefinition
FunctionTemplate
TemplateParamDeclaration: placeholder
class typeIdentifier
typename variableIdentifier
7/27/2019 OOPs Unit-III
8/47
Example of a Function Template
template
void Print( SomeType val ){
cout
7/27/2019 OOPs Unit-III
9/47
Instantiating a Function
Template When the compiler instantiates a template,
it substitutes the template argument for the
template parameterthroughout the functiontemplate.
Function < TemplateArgList > (FunctionArgList)
TemplateFunction Call
7/27/2019 OOPs Unit-III
10/47
Summary of Three Approaches
Nave Approach
Different Function Definitions
Different Function Names
Function Overloading
Different Function Definitions
Same Function Name
Template Functions
One Function Definition (a function template)Compiler Generates Individual Functions
7/27/2019 OOPs Unit-III
11/47
Class Template A C++ language construct that allows the compilerto generate multiple versions of a class by allowing
parameterized data types.
Template < TemplateParamList >
ClassDefinition
Class Template
TemplateParamDeclaration: placeholder
class typeIdentifier
typename variableIdentifier
7/27/2019 OOPs Unit-III
12/47
Example of a Class Template
templateclass GList{public:
bool IsEmpty() const;bool IsFull() const;int Length() const;void Insert( /* in */ ItemType item );void Delete( /* in */ ItemType item );
bool IsPresent( /* in */ ItemType item ) const;void SelSort();
void Print() const;GList(); // Constructorprivate:
int length;ItemType data[MAX_LENGTH];
};
Template
parameter
7/27/2019 OOPs Unit-III
13/47
Instantiating a Class Template
Class template arguments mus tbe
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.
7/27/2019 OOPs Unit-III
14/47
Instantiating a Class Template
// Client code
GList list1;GList list2;
GList list3;
list1.Insert(356);list2.Insert(84.375);list3.Insert("Muffler bolt");
To create lists of different data types
GList_int list1;GList_float list2;GList_string list3;
template argument
Compiler generates 3
distinct class types
7/27/2019 OOPs Unit-III
15/47
Substitution Example
class GList_int{
public:
void Insert( /* in */ ItemType item );
void Delete( /* in */ ItemType item );
bool IsPresent( /* in */ ItemType item ) const;
private:int length;ItemType data[MAX_LENGTH];
};
int
int
int
int
7/27/2019 OOPs Unit-III
16/47
Function Definitions for
Members of a Template Classtemplate
void GList::Insert( /* in */ ItemType item )
{
data[length] = item;
length++;
}
//after substitution of float
void GList::Insert( /* in */ float item ){
data[length] = item;
length++;
}
7/27/2019 OOPs Unit-III
17/47
Another Template Example:
passing two parameters
template
class Stack {...
};
Stack mystack;
non-type parameter
7/27/2019 OOPs Unit-III
18/47
Exception
An exception is a unusual, often
unpredictable event, detectable bysoftware or hardware, that requires
special processing occurring at runtime
In C++, a variable or class object thatrepresents an exceptional event.
7/27/2019 OOPs Unit-III
19/47
Errors can be dealt with at place error occurs
Easy to see if proper error checking implemented
Harder to read application itself and see how code works
Exception handling
Makes clear, robust, fault-tolerant programs
C++ removes error handling code from "main line" of program
Common failures new not allocating memory
Out of bounds array subscript
Division by zero
Invalid function parameters
7/27/2019 OOPs Unit-III
20/47
Exception handling - catch errors before they occur
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
Exception handling should not be used for program
control
Not optimized, can harm program performance
7/27/2019 OOPs Unit-III
21/47
Exception handling improves fault-tolerance
Easier to write error-processing code
Specify what type of exceptions are to be caught
Most programs support only single threads
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
7/27/2019 OOPs Unit-III
22/47
Handling Exception
If without handling,
Program crashes
Falls into unknown state
An exception handleris 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
7/27/2019 OOPs Unit-III
23/47
Standard Exceptions
Exceptions Thrown by the Language
new
Exceptions Thrown by StandardLibrary Routines
Exceptions Thrown by user code,
usingthrow
statement
7/27/2019 OOPs Unit-III
24/47
When Exception Handling Should Be
Used
Error handling should be used for
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
7/27/2019 OOPs Unit-III
25/47
Basics of C++ Exception Handling: try,
throw, catch
A function can throw an exception object if it detects
an error
Object typically a character string (error message) orclass object
If exception handler exists, exception caught and
handled
Otherwise, program terminates
7/27/2019 OOPs Unit-III
26/47
Basics of C++ Exception Handling:try, throw, catch (II)
Format
Enclose code that may have an error in try block
Follow with one or more catch blocks Each catch block has an exception handler
If exception occurs and matches parameter in catch
block, code in catch block executed
If no exception thrown, exception handlers skipped andcontrol resumes after catch blocks
throw point - place where exception occurred
Control cannot return to throw point
throw indicates an exception has occurred
7/27/2019 OOPs Unit-III
27/47
throw - indicates an exception has occurred
Usually has one operand (sometimes zero) of any type
If operand an object, called an exception object
Conditional expression can be thrown
Code referenced in a try block can throw an exception
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
7/27/2019 OOPs Unit-III
28/47
The throwStatement
Throw: to signal the fact that an
exception has occurred; also called
raise
ThrowStatement throw Expression
7/27/2019 OOPs Unit-III
29/47
Exception handlers are in catch blocks
Format: catch( exceptionTypeparameterName){
exception handling code}
Caught if argument type matches throwtype
If not caught then terminate called which (by default)
calls abort Example:catch ( DivideByZeroException ex) {
cout
7/27/2019 OOPs Unit-III
30/47
Catch all exceptions
catch(...) - catches all exceptions
You do not know what type of exception occurred There is no parameter name - cannot reference the object
If no handler matches thrown object
Searches next enclosing try block If none found, terminate called
If found, control resumes after last catch block
If several handlers match thrown object, first one found
is executed
7/27/2019 OOPs Unit-III
31/47
catch parameter matches thrown object when
They are of the same type
Exact match required - no promotions/conversionsallowed
The catch parameter is apublic base class of the
thrown object
The catch parameter is a base-class pointer/
reference type and the thrown object is a derived-classpointer/ reference type
The catch handler is catch(...)
Thrown const objects have const in the parameter
type
7/27/2019 OOPs Unit-III
32/47
Unreleased resources
Resources may have been allocated when exception
thrown
catch handler should delete space allocated by new
and close any opened files
catch handlers can throw exceptions
Exceptions can only be processed by outertry blocks
7/27/2019 OOPs Unit-III
33/47
The try-catchStatement
try
Blockcatch (FormalParameter)
Blockcatch (FormalParameter)
TryCatchStatement
How one part of the program catches and processesthe exception that another part of the program throws.
FormalParameter
DataType VariableName
7/27/2019 OOPs Unit-III
34/47
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
}
catch ( string s )
{
cout
7/27/2019 OOPs Unit-III
35/47
Execution oftry-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 exceptionhandler
7/27/2019 OOPs Unit-III
36/47
Throwing an Exception to be
Caught by the Calling Code
void Func4(){
if ( error )throw ErrType();
}
Normal
return
void Func3(){
try
{
Func4();
}catch ( ErrType ){
}
}
Function
call
Return from
thrown
exception
7/27/2019 OOPs Unit-III
37/47
Practice: Dividing by ZERO
Apply what you know:
int Quotient(int numer, // The numerator
int denom ) // The denominator
{if (denom != 0)
return numer / denom;
else
//What to do?? do sth. to avoid program//crash
}
7/27/2019 OOPs Unit-III
38/47
int Quotient(int numer, // The numerator
int denom ) // The denominator
{
if (denom == 0)
throw DivByZero();
//throw exception of class DivByZero
return numer / denom;
}
A Solution
7/27/2019 OOPs Unit-III
39/47
A Solution
// quotient.cpp -- Quotient program
#include#include
int Quotient( int, int );
class DivByZero {}; // Exception class
int main()
{
int numer; // Numerator
int denom; // Denominator
//read in numerator
and denominator
while(cin)
{try{
cout
7/27/2019 OOPs Unit-III
40/47
Take Home Message
Templates are mechanisms for generating functions andclasses on type parameters. We can design a single classor function that operates on data of many types
function templates
class templates
An exception is a unusual, often unpredictable event thatrequires special processing occurring at runtime
throw
try-catch
7/27/2019 OOPs Unit-III
41/47
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 // Fig. 23.2: fig23_02.cpp
7/27/2019 OOPs Unit-III
42/47
1. Load header
1.1 Function prototype
2 // Demonstration of rethrowing an exception.
3 #include
4
5 using std::cout;
6 using std::endl;
7
8 #include
9
10 using std::exception;
11
12 voidthrowException()
13 {
14 // Throw an exception and immediately catch it.
15 try {
16 cout
7/27/2019 OOPs Unit-III
43/47
2. Function call
3. Output
23 }
24
25 cout
7/27/2019 OOPs Unit-III
44/47
Exception specification (throw list) Lists exceptions that can be thrown by a function
Example:
int g( double h ) throw ( a, b, c )
{// function body
}
Function can throw listed exceptions or derived types
If other type thrown, function unexpectedcalled
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 nothrow
list specified, function canthrow
any exception
Function unexpected
7/27/2019 OOPs Unit-III
45/47
p Calls the function specified with set_unexpected
Default:terminate
Function terminate Calls function specified withset_terminate
Default: abort
set_terminate and set_unexpected Prototypes in
Take pointers to functions (i.E., Function name) Function must return voidand take no arguments
Returns pointer to last function called by terminate orunexpected
7/27/2019 OOPs Unit-III
46/47
Uncaught Exception
Function-call stack unwound when exception
thrown and not caught in a particular scope Tries to catch exception in next outertry/catch
block
Function in which exception was not caughtterminates
Local variables destroyed
Control returns to place where function was
called If control returns to a try block, attempt made tocatch exception
Otherwise, further unwinds stack
If exception not caught, terminate called
Constr ctors Destr ctors and
7/27/2019 OOPs Unit-III
47/47
Constructors, Destructors and
Exception Handling
What to do with an error in a constructor?
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