0% found this document useful (0 votes)
1 views48 pages

CHAPTER 4 ExceptionHandling Templates

Module-04 covers exception handling and templates in C++. It explains how exceptions indicate problems during program execution and how C++ provides a robust mechanism for handling these exceptions, similar to Java. Additionally, it introduces function and class templates, allowing for generic programming and code reusability in C++.

Uploaded by

ai.verrse6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views48 pages

CHAPTER 4 ExceptionHandling Templates

Module-04 covers exception handling and templates in C++. It explains how exceptions indicate problems during program execution and how C++ provides a robust mechanism for handling these exceptions, similar to Java. Additionally, it introduces function and class templates, allowing for generic programming and code reusability in C++.

Uploaded by

ai.verrse6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Module-04

Exception handling and Templates


in C++

© 2006 Pearson Education, Inc. All rights reserved.


Introduction
• Exceptions
– Indicate problems that occur during a program’s
execution.
– Occur infrequently
• Exception handling
– Can resolve exceptions
• Allow a program to continue executing or
• Notify the user of the problem and
• Terminate the program in a controlled manner
– Makes programs robust and fault-tolerant

© 2006 Pearson Education, Inc. All rights reserved.


Exception Handling in C++

• A standard mechanism for processing errors


– Especially important when working on a project
with a large team of programmers

• C++ exception handling is much like Java’s

• Java’s exception handling is much like C++

© 2006 Pearson Education, Inc. All rights reserved.


Fundamental Philosophy

• Mechanism for sending an exception signal


up the call stack
• Regardless of intervening calls

• Note: there is a mechanism based on same


philosophy in C
• setjmp(), longjmp()
• See man pages

© 2006 Pearson Education, Inc. All rights reserved.


Fundamental Philosophy (continued)

• Remove error-handling code from the


program execution’s “main line”

• Programmers can handle any exceptions


they choose
– All exceptions
– All exceptions of a certain type
– All exceptions of a group of related types

© 2006 Pearson Education, Inc. All rights reserved.


Fundamental Philosophy (continued)

• Programs can
– Recover from exceptions
– Hide exceptions
– Pass exceptions up the “chain of command”
– Ignore certain exceptions and let someone else
handle them

© 2006 Pearson Education, Inc. All rights reserved.


Fundamental Philosophy (continued)

• An exception is a class
• Usually derived from one of the system’s exception
base classes
• If an exceptional or error situation occurs,
program throws an object of that class
• Object crawls up the call stack

• A calling program can choose to catch


exceptions of certain classes
• Take action based on the exception object

© 2006 Pearson Education, Inc. All rights reserved.


Class exception

• The standard C++ base class for all


exceptions
• Provides derived classes with virtual
function what
– Returns the exception’s stored error message

CS-2303, C-Term 2010 Exception Handling in 8


C++
© 2006 Pearson Education, Inc. All rights reserved.
Example: Handling an Attempt to Divide by
Zero

CS-2303, C-Term 2010 Exception Handling in 9


C++
© 2006 Pearson Education, Inc. All rights reserved.
Explanation

• The divide function checks if the denominator is zero


and throws an exception if it is.
• The main function calls divide inside a try block.
• If an exception occurs, it is caught by the catch block,
which prints the error message.
• The program does not terminate unexpectedly and
continues execution after handling the exception.

CS-2303, C-Term 2010 Exception Handling in 10


C++
© 2006 Pearson Education, Inc. All rights reserved.
try Blocks

• Keyword try followed by braces ({})


• Should enclose
– Statements that might cause exceptions
– Statements that should be skipped in case of an
exception

11

© 2006 Pearson Education, Inc. All rights reserved.


Software Engineering Observation

• Exceptions may surface


– through explicitly mentioned code in a try
block,
– through calls to other functions and
– through deeply nested function calls initiated by
code in a try block.

12

© 2006 Pearson Education, Inc. All rights reserved.


Catch Handlers

• Immediately follow a try block


– One or more catch handlers for each try block
• Keyword catch
• Exception parameter enclosed in parentheses
– Represents the type of exception to process
– Can provide an optional parameter name to interact
with the caught exception object
• Executes if exception parameter type matches the
exception thrown in the try block
– Could be a base class of the thrown exception’s class
CS-2303, C-Term 2010 Exception Handling in 13
C++
© 2006 Pearson Education, Inc. All rights reserved.
Catch Handlers (continued)
try { All other classes of exceptions
// code to try
are not handled here
}
catch (exceptionClass1 &name1) {
// handle exceptions of exceptionClass1
}
catch (exceptionClass2 &name2) {
// handle exceptions of exceptionClass2
}
catch (exceptionClass3 &name3) {
// handle exceptions of exceptionClass3
}
... catch clauses attempted
/* code to execute if in order; first match wins!
no exception or
catch handler handled exception*/
CS-2303, C-Term 2010 Exception Handling in 14
C++
© 2006 Pearson Education, Inc. All rights reserved.
Common Programming Errors

• Syntax error to place code between a try block


and its corresponding catch handlers

• Each catch handler can have only a single


parameter
• Specifying a comma-separated list of exception parameters is a
syntax error

• Logic error to catch the same type in two different


catch handlers following a single try block

CS-2303, C-Term 2010 Exception Handling in 15


C++
© 2006 Pearson Education, Inc. All rights reserved.
Throwing an Exception

• Use keyword throw followed by an


operand representing the type of exception
– The throw operand can be of any type
– If the throw operand is an object, it is called an
exception object
• The throw operand initializes the exception
parameter in the matching catch handler, if
one is found

CS-2303, C-Term 2010 Exception Handling in 16


C++
© 2006 Pearson Education, Inc. All rights reserved.
Exception Handling Summary

• Exceptions are derived from class exception


• Exceptional or error condition is indicated by
throwing an object of that class
• Created by constructor in throw statement
• Calling programs can check for exceptions
with try...catch construct
• Unified method of handling exceptions
• Far superior to coding exception handling in long hand
• No performance impact when no exceptions
CS-2303, C-Term 2010 Exception Handling in 17
C++
© 2006 Pearson Education, Inc. All rights reserved.
Introduction to C++ Templates

• C++ Function Templates


• C++ Class Templates

© 2006 Pearson Education, Inc. All rights reserved.


C++ Function Templates
• Approaches for functions that implement identical tasks
for different data types
– Naïve Approach

– Function Overloading

– Function Template

• Function templates in C++ can be a generic function for


swapping two values.
• Consider a scenario where you need to swap integers,
floating-point numbers, or even characters.
• Instead of writing multiple functions for each data type, you
can use a function template.

© 2006 Pearson Education, Inc. All rights reserved.


Approach 1: Naïve 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

© 2006 Pearson Education, Inc. All rights reserved.


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);
© 2006 Pearson Education, Inc. All rights reserved.
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 results
caused by using the wrong function name.

© 2006 Pearson Education, Inc. All rights reserved.


Example of Function Overloading
void Print( int n )
{
cout << "***Debug" << endl;
cout << "Value is " << n << endl;
}
void Print( char ch )
{
cout << "***Debug" << endl;
cout << "Value is " << ch << endl;
}
void Print( float x ) To output the traced values, we insert:
{
Print(someInt);
}
Print(someChar);
Print(someFloat);

© 2006 Pearson Education, Inc. All rights reserved.


Approach 3: Function Template
• A C++ language construct that allows the compiler to
generate multiple versions of a function by allowing
parameterized data types.

FunctionTemplate
Template < TemplateParamList
>
FunctionDefinition
TemplateParamDeclaration: placeholder

class typeIdentifier
typename variableIdentifier

© 2006 Pearson Education, Inc. All rights reserved.


Example of a Function Template
Template parameter
template<class SomeType>
(class, user defined
void Print( SomeType val ) type, built-in types)
{
cout << "***Debug" << endl;
cout << "Value is " << val << endl;
}

Template To output the traced values, we insert:


argument Print<int>(sum);
Print<char>(initial);
Print<float>(angle);

© 2006 Pearson Education, Inc. All rights reserved.


Instantiating a Function Template
• When the compiler instantiates a template,
it substitutes the template argument for the
template parameter throughout the function
template.

TemplateFunction Call

Function < TemplateArgList > (FunctionArgList)

© 2006 Pearson Education, Inc. All rights reserved.


Summary of Three Approaches
Naïve Approach
Function Overloading
Different Function
Different Function Definitions
Definitions
Same Function Name
Different Function Names

Template Functions
One Function Definition (a function template)
Compiler Generates Individual Functions

© 2006 Pearson Education, Inc. All rights reserved.


Class Template
• A C++ language construct that allows the compiler to generate
multiple versions of a class by allowing parameterized data
types.
•Example: Generic Stack class, which can store different data
types (integers, floats, strings, double etc.) without rewriting the
class for each type.

Class Template
Template < TemplateParamList
>
ClassDefinition
TemplateParamDeclaration: placeholder

class typeIdentifier
typename variableIdentifier

© 2006 Pearson Education, Inc. All rights reserved.


Example of a Class Template
template<class ItemType>
class GList
{ Template
public: parameter
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(); // Constructor
private:
int length;
ItemType data[MAX_LENGTH];
};

© 2006 Pearson Education, Inc. All rights reserved.


Instantiating a Class Template
• 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.
© 2006 Pearson Education, Inc. All rights reserved.
Instantiating a Class Template
To create lists of different data types
// Client code
template argument
GList<int> list1;
GList<float> list2;
GList<string> list3;

list1.Insert(356); Compiler generates 3


list2.Insert(84.375); distinct class types
list3.Insert("Muffler bolt");
GList_int list1;
GList_float list2;
GList_string list3;

© 2006 Pearson Education, Inc. All rights reserved.


Substitution Example

class GList_int
{
public: int

void Insert( /* in */ ItemType item );


int
void Delete( /* in */ ItemType item );

bool IsPresent( /* in */ ItemType item ) const;

private: int
int length;
ItemType data[MAX_LENGTH];
};
int

© 2006 Pearson Education, Inc. All rights reserved.


Standard Template Library (STL)
• In the late 70s Alexander Stepanov first observed that
some algorithms do not depend on some particular
implementation of a data structure but only on a few
fundamental semantic properties of the structure.
• Developed by Stepanov and Lee at HP labs in 1992.
• Become part of the C++ Standard in 1994.
• It used to simplify the development of C++ programs.
• The Standard Template Library (STL) in C++ can be
a grocery store billing system, where we store item
names and their prices using STL containers like
vector and map.
© 2006 Pearson Education, Inc. All rights reserved.
What’s in STL?
• Container classes/iterators as vector, list, stack,
array, set, map, and etc…
• It can be used to store and manipulate data.
• A large collection of algorithms, such as reverse,
swap, heap, and etc.
• Algorithms for searching, sorting and
manipulating data.
• It provides a way to write generic, reusable code
that can be applied to different data types.

© 2006 Pearson Education, Inc. All rights reserved.


Detail
Container Description Header file iterator

vector is a class that creates a dynamic array allowing insertions and deletions at the
vector <vector> Random access
back.

list list is the sequence containers that allow the insertions and deletions from anywhere. <list> Bidirectional

deque is the double ended queue that allows the insertion and deletion from both the
deque <deque> Random access
ends.

set set is an associate container for storing unique sets. <set> Bidirectional

multiset Multiset is an associate container for storing non- unique sets. <set> Bidirectional

Map is an associate container for storing unique key-value pairs, i.e. each key is
map <map> Bidirectional
associated with only one value(one to one mapping).

multimap is an associate container for storing key- value pair, and each key can be
multimap <map> Bidirectional
associated with more than one value.

stack It follows last in first out(LIFO). <stack> No iterator


queue It follows first in first out(FIFO). <queue> No iterator
Priority-queu
First element out is always the highest priority element. <queue> No iterator
e

© 2006 Pearson Education, Inc. All rights reserved.


Vector

• A sequence that supports random access to


elements.
– Elements can be inserted and removed at the
beginning, the end and the middle.
– Constant time random access.
– Commonly used operations
• begin(), end(), size(), [], push_back(…), pop_back(),
insert(…), empty()

© 2006 Pearson Education, Inc. All rights reserved.


Map
– An indexed collection, similar to the Java
Dictionary or Harshtable.
– Parameterized by two template arguments, key
type and value type.
– Operations are implemented with a data type
called a pair, which is a key/value combination.

37

© 2006 Pearson Education, Inc. All rights reserved.


Stack and Queue
– In STL, they are adapters, built on top of an
underlying data type such as a vector or linked
list.
– Adapter: a software component that changes
the interface to another component.
stack< vector<int> > stackOne;
stack< list<anObject *> > stackTwo;
queue< deque<double> > queueOne

38

© 2006 Pearson Education, Inc. All rights reserved.


Iterators

• The concept of an iterator in the STL is


similar to Enumeration in Java but differs in
the particulars of use.

39

© 2006 Pearson Education, Inc. All rights reserved.


Iterators
• Not need to cast the object to the proper type after
it has been removed from the container.
• Containers can store primitive types and do not
need the wrapper class necessitated by the Java
version.
• To create an iterator, first requires specifying the
container type.
• Iterators must be manipulated in pairs with a
beginning and an ending iterator.

40

© 2006 Pearson Education, Inc. All rights reserved.


Iterators

• Designed to be equivalent – and compatible


with – conventional pointers.
• Can be used to denote a specific vale.
• A pair of iterators can be used to describe a
range of values.

41

© 2006 Pearson Education, Inc. All rights reserved.


Iterators

• Iterators produced by containers often come


in pairs.
• The beginning iterator is returned by the
function begin, and the ending iterator by
the function end.

© 2006 Pearson Education, Inc. All rights reserved.


Example
template <class iterator, class T>
iterator find (iterator first, iterator last, T & value)
{
while (first != last && *first != value)
++first;
return first;
}

int data[100];
...
int * where = find(data, data+100, 7);

list<int>::iterator where = find(aList.begin(), aList.end(), 7);

43

© 2006 Pearson Education, Inc. All rights reserved.


Generic Algorithms

• Generic algorithm: a software algorithm that


can be used with many different collection
classes.
random_shuffle (cards, cards+52, randomizer);

44

© 2006 Pearson Education, Inc. All rights reserved.


Function Objects
• Function object: an object that can be uesd in the
fashion of a function.

class randomInteger {
public:
unsigned int operator () (unsigned int max) {
// compute rand value between 0 and max
unsigned int rval = rand();
return rval % max;
}
};

randomInteger randomizer; // create an instance of class

45

© 2006 Pearson Education, Inc. All rights reserved.


Function Objects

class LargerThan {
public:
// constructor
LargerThan (int v) { val = v; }
// the function call operator
bool operator () (int test)
{ return test > val; }
private:
int val;
};

LargerThan tester(12); // create the predicate function


list<int>::iterator found =
find_if (aList.begin(), aList.end(), tester);
if (found != aList.end())
printf("element is %d", *found); // found such a value
else
46
printf("no element larger than 12");
© 2006 Pearson Education, Inc. All rights reserved.
Function Objects
LargerThan(12) // creates an instance of LargerThan

list<int>::iterator found =
find_if (aList.begin(), aList.end(), LargerThan(12));

class charCompare { // compare two character literal values


public:
bool operator () (const char * left, const char * right) const
{
return strcmp(left, right) < 0;
}
};

typedef map <const char *, unsigned int, charCompare> cityInfo;

47

© 2006 Pearson Education, Inc. All rights reserved.


THANK YOU

© 2006 Pearson Education, Inc. All rights reserved.

You might also like