Chapter 16 - PowerPoint PPT Presentation

1 / 38
About This Presentation
Title:

Chapter 16

Description:

Exceptions are used to signal errors or unexpected events that ... multimap. Maps a set of keys to data elements. Only one key per data element is allowed. ... – PowerPoint PPT presentation

Number of Views:82
Avg rating:3.0/5.0
Slides: 39
Provided by: stephen131
Category:
Tags: chapter | multimap

less

Transcript and Presenter's Notes

Title: Chapter 16


1
Chapter 16 Exceptions, Templates, and the
Standard Template Library (STL)
  • Exceptions are used to signal errors or
    unexpected events that occur while a program is
    running.
  • We have checked for errors before by placing if
    statements that checked for the condition or by
    using assert statements.

2
Exceptions (cont)
  • An exceptional condition is a value or an object
    that signals an error.
  • When the error occurs, an exception is thrown.

3
Throwing an Exception
  • RationalRational ( int numerator, int
    denominator )
  • if ( denominator 0 )
  • throw "ERROR Cannot divide by zero.\n"
  • this-gtnumerator numerator
  • this-gtdenominator denominator
  • // divide

4
Throw
  • The line containing a throw statement is called
    the throw point.
  • When a throw statement is executed, control is
    passed to an exception handler.
  • When an exception is thrown by a function, the
    function aborts.
  • Any type can be thrown

5
Handling an Exception
  • An exception is handled by a try/catch construct.
  • The try block contains a block of code that may
    directly or indirectly cause an exception to be
    thrown.
  • The catch block contains a block of code that
    handles the exception.

6
Example Exception Handler
  • try
  • Rational q Rational( num1, num2 )
  • cout ltlt q ltlt endl
  • // try
  • catch ( char exceptionString )
  • cout ltlt exceptionString
  • // catch

7
Handling an Exception (cont)
  • If divide throws an exception, the exception is
    caught by the catch statement.
  • The type of the parameter to the catch statement
    must be the same as in the throw statement (or
    class from which it is derived).
  • Execution continues after the try/catch
    statement, unless the catch statement does
    something else.

8
Uncaught Exceptions
  • Ways for uncaught exceptions
  • No catch statement with a parameter of the
    correct data type.
  • The exception is thrown outside a try statement.
  • In either case, the exception causes the program
    to abort.

9
More on Exceptions
  • Exceptions can be put in classes. This allows us
    to do more with them.
  • We can have multiple exception classes.
  • Exception classes can have parameters that allow
    information to be returned.

10
IntMain.cpp Program (cont)
  • in getInput
  • throw OutOfRange( input )
  • in main
  • try
  • userValue range.getInput()
  • cout ltlt "You entered " ltlt uservalue ltlt endl
  • // try
  • catch ( IntRangeOutOfRange ex )
  • cout ltlt "That value " ltlt ex.value
  • ltlt " is out of range." ltlt endl
  • // catch
  • cout ltlt "End of program." ltlt endl
  • // main

11
Class for exceptions
  • class BadTrait
  • private
  • string msg
  • public
  • BadTrait(string errorMsg, int val)
  • char str10
  • itoa(val,str,10) // integer, string to
    convert to, number sys
  • msg errorMsgstr
  • string getMsg() return msg

12
How to Throw
  • // add newEle to set only if it is a legal
    element
  • Set Setoperator(int newEle)
  • if (newEle ltmemberMax newEle gt0)
  • membernewEletrue
  • else throw BadTrait("Error Adding element
    which is out of range " , newEle)
  • return this

13
How to catch
  • try
  • Traits me
  • me4 me 5me 11 me 27
  • catch (BadTrait b)
  • coutltlt b.getMsg() ltlt endl

14
Unwinding the Stack
  • When an exception is thrown, the function
    immediately terminates.
  • If that function was called by another function,
    then the calling function terminates as well.
  • This process continues.
  • This is called unwinding the stack.

15
Function Templates
  • A function template is a generic function that
    can work with any data type.
  • The programmer writes the specifications of the
    function, but substitutes parameters for data
    types.
  • When the compiler encounters a call to the
    function, it generates code to handle the
    specific data type(s) used in the call.

16
Template Example
  • We want a function that prints out the values of
    an array.
  • This function should work with arrays of type
    int, float, char, or string.

17
printArray.cpp Program
  • include ltiostreamgt
  • include ltstringgt
  • using namespace std
  • templatelt class Tgt
  • void printArray ( const T array, const int size
    )
  • for ( int i 0 i lt size i )
  • if ( !( i 10 ) )
  • cout ltlt endl
  • cout ltlt arrayi ltlt " "
  • // for
  • cout ltlt endl
  • // printArray

18
printArray.cpp Program (cont)
  • void main ( void )
  • const int aSize 5, bSize 7, cSize 6,
    dSize 3
  • int a aSize 1, 2, 3, 4, 5
  • float b bSize 1.1, 2.2, 3.3, 4.4, 5.5,
    6.6, 7.7
  • char c cSize "Hello"
  • string d dSize "I", "love", "CS"
  • printArray( a, aSize )
  • printArray( b, bSize )
  • printArray( c, cSize )
  • printArray( d, dSize )
  • // main

19
Generic swap
  • Suppose we wanted a generic swap.
  • template ltclass Tgt
  • void swap ( T var1, T var2 )
  • T temp
  • temp var1
  • var1 var2
  • var2 temp
  • // swap

20
Template with Multiple Types
  • template ltclass T1, class T2gt
  • void swap ( T1 var1, T2 var2 )
  • T1 temp
  • temp var1
  • var1 (T1)var2
  • var2 (T2)temp
  • // swap

21
Operators in Template
  • If arithmetic or relational operators are used in
    templates, they must be defined for the different
    types of the templates.
  • If the operators are not defined for a particular
    type, the compiler generates an error.

22
Class Templates
  • Templates may also be used to create generic
    classes and abstract data types.
  • Class templates allow you to create one general
    version of a class without having to duplicate
    code to handle multiple data types.

23
Generic Class
  • Suppose you wanted to have a class that held a
    collection of objects.
  • We want this class to work with different data
    types.
  • We could create a different class for each data
    type, but there is a better solution.
  • We will look at a class template.

24
SimpleVector.h Program
  • template ltclass Tgt
  • Class SimpleVector
  • private
  • T aptr
  • int arraySize
  • public
  • SimpleVector ( void ) aptr NULL
    arraySize 0
  • SimpleVector ( int )
  • SimpleVector ( const SimpleVector )
  • SimpleVector ( void )
  • int getSize ( void ) return arraySize
  • T operator ( const int )
  • // SimpleVector

25
SimpleVector.cpp Program
  • template ltclass Tgt
  • SimpleVectorltTgtSimpleVector ( int s )
  • arraySize s
  • aptr new T s
  • assert( aptr )
  • for ( int i 0 i lt arraySize i )
  • ( aptr i ) 0
  • // SimpleVectorSimpleVector
  • template ltclass Tgt
  • SimpleVectorltTgtSimpleVector ( void )
  • if ( arraySize gt 0 )
  • delete aptr
  • // SimpleVectorSimpleVector

26
Declaring Objects of Class Templates
  • The declaration of class templates is a little
    different.
  • Consider the following examples
  • SimpleVectorltintgt intTable ( 10 )
  • SimpleVectorltfloatgt floatTable ( 10 )
  • In these, the parameter inside the angle brackets
    replaces the T in the previous declarations.

27
Class Templates and Inheritance
  • ifndef SEARCHABLEVECTOR_H
  • define SEARCHABLEVECTOR_H
  • include SimpleVector.h
  • template ltclass Tgt
  • class SearchableVector public SimpleVectorltTgt
  • public
  • SearchableVector ( int s )
    SimpleVectorltTgt( s )
  • SearchableVector ( SearchableVector )
  • SearchableVector ( SimpleVectorltTgt obj )
  • SimpleVectorltTgt( obj )
  • int findItem ( T )
  • // SearchableVector

28
Introduction to the Standard Template Library
(STL)
  • The Standard Template Library contains many
    templates for useful algorithms and data
    structures.
  • Weve seen on of these earlier in the book the
    vector data type.

29
Abstract Data Types
  • The most important data structures in STL are
    containers and iterators
  • Container a class that stores data and
    organizes it in some fashion.
  • Iterator similar to a pointer and is used to
    access the individual data elements in a
    container.

30
Container Classes
  • Sequence organizes data in a sequential fashion
    similar to an array.
  • Associative uses keys to rapidly access
    elements in the data structure.

31
Sequence Containers
32
Associative Containers
33
Iterators
34
More on Iterators
  • Iterators are associated with containers.
  • The type of container you have determines the
    type of iterator you use.
  • For example, vectors and deques require
    random-access iterators.
  • Lists, sets, multisets, maps, and multimaps
    require bidirectional iterators.

35
Algorithms
  • Algorithms are implemented as function templates.
  • They perform various operations on elements of
    containers.

36
Description of Some Algorithms
37
Using Vectors Program
  • include ltiostreamgt
  • include ltvectorgt
  • include ltalgorithmgt
  • using namespace std
  • void doubleValue ( int val )
  • val 2
  • // doubleValue
  • void main ( void )
  • vectorltintgt numbers
  • vectorltintgtiterator iter

38
Using Vectors Program (cont)
  • for ( int x 0 x lt 10 x )
  • numbers.push_back( x )
  • cout ltlt The numbers in the vector are\n
  • for ( iter numbers.begin() iter !
    numbers.end() iter )
  • cout ltlt iter ltlt endl
  • cout ltlt endl
  • for_each ( numbers.begin(), numbers.end(),
    doubleValue )
  • cout ltlt The numbers again are\n
  • for ( iter numbers.begin() iter !
    numbers.end() iter )
  • cout ltlt iter ltlt endl
  • cout ltlt endl
  • // main
Write a Comment
User Comments (0)
About PowerShow.com