Templates and Exception Handling
Templates and Exception Handling
Contents
• Generic functions
• Generic classes
• Exception handling
• Exercises
Generic Functions
• Using templates, it is possible to create generic functions and classes.
• A generic function defines a general set of operations that will be applied to various
data types.
• By creating a generic function, you can define, independent of any data, the nature of
the algorithm.
• In essence, when you create a generic function you are creating a function that can
automatically overload itself.
• It is used to create template (or framework) that describes what a function will do.
Generic Classes
• In addition to defining generic functions, you can also define generic
classes.
• When you do this, you create a class that defines all algorithms used by that
class, but the actual type of the data being manipulated will be specified as a
parameter when objects of that class are created.
• Using exception handling, you can more easily manage and respond to run-time
errors.
• C++ exception handling is built upon three keywords: try, catch, and throw.
• If an exception (i.e., an error) occurs within the try block, it is thrown (using
throw). The exception is caught, using catch, and processed.
• The try block must contain the portion of your program that you want to monitor
for errors.
More About Exception Handling
• In some circumstances you will want an exception handler to catch all
exceptions instead of just a certain type. This is easy to accomplish. Simply
use this form of catch:
catch(…){
//process all exceptions
• You can control what type of exceptions a function can throw outside of itself.
• To apply these restrictions, you must add a throw clause to the function
definition.
Handling Exceptions Thrown By new
• In C++, when an allocation request cannot be honored, new throws a
bad_alloc exception.
• To have access to this exception, you must include header <new> in your
program.
Exercises
• Create a templated Stack class that can store elements of any data type (e.g.,
int, double, string). Implement push, pop, and top functions. Test it with
various data types.
• Create a class MathOperation that has a method for dividing two numbers.
Use exception handling to catch and handle the division by zero error.