Starting Out with C++, 3 rd Edition 1 Chapter 16 – Exceptions, Templates, and the Standard Template Library (STL) Exceptions are used to signal errors.

Slides:



Advertisements
Similar presentations
M The University Of Michigan Andrew M. Morgan EECS Lecture 22 Savitch Ch. 16 Intro To Standard Template Library STL Container Classes STL Iterators.
Advertisements

C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
1 Chapter 17-2 Templates and Exceptions Dale/Weems.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Starting Out with C++, 3 rd Edition 1 Chapter 16 – Exceptions, Templates, and the Standard Template Library (STL) Exceptions are used to signal errors.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Object Oriented Programming Elhanan Borenstein Lecture #12 copyrights © Elhanan Borenstein.
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
1 CSC241: Object Oriented Programming Lecture No 28.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
More on the STL vector list stack queue priority_queue.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 16 Exceptions,
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Introduction to C++ Templates and Exceptions l C++ Function Templates l C++ Class Templates l Exception and Exception Handler.
Templates and the STL.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
1 CSC241: Object Oriented Programming Lecture No 27.
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
Data Structures Using C++ 2E
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Pointers OVERVIEW.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan and A. Ranade.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 16: Exceptions,
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 Arrays and Vectors Chapter 7 Arrays and Vectors Chapter 7.
HANDLING EXCEPTIONS Chapter 9. Outline  Learn about the limitations of traditional error-handling methods  Throw exceptions  Use try blocks  Catch.
Review 1 List Data Structure List operations List Implementation Array Linked List.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
LECTURE LECTURE 14 Exception Handling Textbook p
1 Chapter 17 Templates and Exceptions Dale/Weems.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.
Exception Handling How to handle the runtime errors.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Templates Linked Lists.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Exceptions Exceptions are used to signal that an unexpected event has happened in a program C++ will generate exceptions for some errors in the program.
CS 2704 Object Oriented Software Design and Construction
C++ Templates.
Exceptions, Templates, and the Standard Template Library (STL)
Why exception handling in C++?
Starting Out with C++ Early Objects Eighth Edition
Chapter 17 Templates and Exceptions Part 2
Exceptions and Templates
Exception Handling.
Exceptions 1 CMSC 202.
Standard Version of Starting Out with C++, 4th Edition
Exceptions, Templates, and the Standard Template Library (STL)
CMSC 202 Lesson 20 Exceptions 1.
Presentation transcript:

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 2 Exceptions (cont) An exceptional condition is a value or an object that signals an error. When the error occurs, an exception is “thrown.”

Starting Out with C++, 3 rd Edition 3 Throwing an Exception Rational::Rational ( int numerator, int denominator ) { if ( denominator == 0 ) throw "ERROR: Cannot divide by zero.\n"; this->numerator = numerator; this->denominator = denominator; } // divide

Starting Out with C++, 3 rd Edition 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”

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 6 Example Exception Handler try { Rational q = Rational( num1, num2 ); cout << q << endl; } // try catch ( char *exceptionString ) { cout << exceptionString; } // catch

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 10 IntMain.cpp – Program (cont) in getInput… throw OutOfRange( input ); in main… try { userValue = range.getInput(); cout << "You entered " << uservalue << endl; } // try catch ( IntRange::OutOfRange ex ) { cout << "That value " << ex.value << " is out of range." << endl; } // catch cout << "End of program." << endl; } // main

Starting Out with C++, 3 rd Edition 11 Class for exceptions class BadTrait{ private: string msg; public: BadTrait(string errorMsg, int val){ char str[10]; itoa(val,str,10); // integer, string to convert to, number sys msg = errorMsg+str; } string getMsg(){ return msg;} };

Starting Out with C++, 3 rd Edition 12 How to Throw // add newEle to set only if it is a legal element Set &Set::operator+=(int newEle){ if (newEle =0) member[newEle]=true; else throw BadTrait("Error: Adding element which is out of range ", newEle); return *this; }

Starting Out with C++, 3 rd Edition 13 How to catch try{ Traits me; me+=4; me += 5;me +=11; me +=27; }catch (BadTrait b){ cout<< b.getMsg() << endl;}

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition Dynamic Arrays Suppose I wanted an array that changed in size. How would I implement that? What operations would I expect to have?

Starting Out with C++, 3 rd Edition Magic Genie Give me what I want. Would I have any concerns?

Starting Out with C++, 3 rd Edition 17 Introduction to the Standard Template Library (STL) The Standard Template Library contains many templates for useful algorithms and data structures. template: a stencil, pattern or overlay used in graphic arts Is a template complete? The Magic Genie

Starting Out with C++, 3 rd Edition 18 Abstract Data Types – what is an abstract data type? 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. Why do we need iterators at all?

Starting Out with C++, 3 rd Edition 19 Container Classes Sequence – organizes data in a sequential fashion similar to an array. “Give me item 7” Associative – uses keys to rapidly access elements in the data structure. “Give me the scissors”

Starting Out with C++, 3 rd Edition 20 Sequence Containers – Has an order Container NameDescription vector An expandable array. Values may be added to or removed from the end (push back) or middle (insert). deque Like a vector, but also allows values to be added to or removed from the front. list A doubly-linked list of data elements. Values may be inserted in or removed from any position. They differ in the underlying representation.

Starting Out with C++, 3 rd Edition Weak Sauce Genie Makes you give him more information. “What are you going to do with it?” Which is better for racing - a general purpose bike or a racing bike? This genie has an attitude. He doesn’t give it the way you want it, but just the way he wants.

Starting Out with C++, 3 rd Edition 22 Associative Containers – stored by value Container NameDescription set Stores a set of keys. No duplicate values are allowed. multiset Stores a set of keys. Duplicates are allowed. map Maps a set of keys to data elements. Only one key per data element is allowed. Duplicates are not allowed. multimap Maps a set of keys to data elements. Many keys per data element are allowed. Duplicates are allowed.

Starting Out with C++, 3 rd Edition So how do associative containers work? Come back next semester…

Starting Out with C++, 3 rd Edition 24 Using Vectors – Program #include using namespace std; void doubleValue ( int &val ) { val *= 2; } // doubleValue void main ( void ) { vector numbers; vector ::iterator iter; // Notice scope resolution operator ::

Starting Out with C++, 3 rd Edition 25 Using Vectors – Program (cont) for ( int x = 0; x < 10; x++ ) numbers.push_back( x ); cout << “The numbers in the vector are:\n”; for ( iter = numbers.begin(); iter != numbers.end(); iter++ ) cout << *iter << endl; cout << endl; for_each ( numbers.begin(), numbers.end(), doubleValue ); cout << “The numbers again are:\n”; for ( iter = numbers.begin(); iter != numbers.end(); iter++ ) cout << *iter << endl; cout << endl; } // main

Starting Out with C++, 3 rd Edition “for each” acts like… for_each(Iterator first, Iterator last, Function f) for ( ; first!=last; ++first ) f(*first);

Starting Out with C++, 3 rd Edition Visit with your neighbor Create a vector of strings. Add the lines of your favorite poem to the vector. Print them out assuming you really can’t remember how many lines you put in.

Starting Out with C++, 3 rd Edition Visit with your neighbor Create a vector of integers. Put in multiples of 5. Print them out, backwards USING ITERATORS.

Starting Out with C++, 3 rd Edition What do you think this does? const int SIZE=5; vector > items ( SIZE, vector ( SIZE ) ); for (int i=0; i < SIZE; i++) for (int j=0; j < SIZE; j++) items[i][j]=i+j; for(int ii=0; ii < SIZE; ii++) { for(int jj=0; jj < SIZE; jj++) { cout << items[ii][jj] << " "; } cout << endl; }

Starting Out with C++, 3 rd Edition What do you think this does? int k=0; vector > things ; for (int i=0; i < SIZE; i++) { things.push_back(vector ()); for (int j=0; j < SIZE; j++) things[i].push_back(k++); } for(int ii=0; ii < SIZE; ii++) { for(int jj=0; jj < SIZE; jj++) { cout << setw(3) << things[ii][jj] << " "; } cout << endl; }

Starting Out with C++, 3 rd Edition What do you think this does? int num_of_col = 5; int num_of_row = 9; const char TREE = 'T'; const char BURNING = '*'; const char EMPTY = ' '; vector > forest; //now we have an empty 2D-matrix of size (0,0). Resizing it with one single command forest.resize( num_of_row, vector ( num_of_col, TREE ) ); for(int ii=0; ii < num_of_row; ii++) { for(int jj=0; jj < num_of_col; jj++) { cout << forest[ii][jj] ; } cout << endl; }

Starting Out with C++, 3 rd Edition 32 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. Given the examples we did for vectors. Can you think of a generic function we may want?

Starting Out with C++, 3 rd Edition When the compiler encounters a call to the function, it generates code to handle the specific data type(s) used in the call. We call this inefficient, right? This is not like inheritance. Tell me the difference.

Starting Out with C++, 3 rd Edition 34 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. In a perfect world (where all these types descended from the same base type), we could use inheritance to make this happen.

Starting Out with C++, 3 rd Edition First, do it for one type – at your seats We want a function that prints out the values of an array. Let’s print out values ten to a line.

Starting Out with C++, 3 rd Edition 36 printArray.cpp – Program #include using namespace std; template void printArray ( const T *array, const int size ) { for ( int i = 0; i < size; i++ ) {if ( !( i % 10 ) ) cout << endl; cout << array[i] << " "; } // for cout << endl; } // printArray

Starting Out with C++, 3 rd Edition 37 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

Starting Out with C++, 3 rd Edition 38 Generic swap Suppose we wanted a generic swap. First do it for one type – at your seats.

Starting Out with C++, 3 rd Edition 39 Generic swap Suppose we wanted a generic swap. template void swap ( T &var1, T &var2 ) { T temp; temp = var1; var1 = var2; var2 = temp; } // swap

Starting Out with C++, 3 rd Edition Suppose we wanted a generic Max function Try it at your seats

Starting Out with C++, 3 rd Edition Suppose we want a generic Max function template T maximum(T a, T b) { return a > b ? a : b ; // Familiar operator? } void main() { cout << "max(10, 15) = " << maximum(10, 15) << endl ; cout << "max('k', 's') = " << maximum('k', 's') << endl ; cout << "max(10.1, 15.2) = " << maximum(10.1, 15.2) << endl ; }

Starting Out with C++, 3 rd Edition 42 Template with Multiple Types template void swap ( T1 &var1, T2 &var2 ) {T1 temp; temp = var1; var1 = (T1)var2; var2 = (T2)temp; } // swap

Starting Out with C++, 3 rd Edition 43 Operators in Template If arithmetic or relational operators are used in templates, they must be defined for the different types of the templates actually passed in. If the operators are not defined for a particular type, the compiler generates an error.

Starting Out with C++, 3 rd Edition 44 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.

Starting Out with C++, 3 rd Edition 45 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.

Starting Out with C++, 3 rd Edition 46 SimpleVector.h – Program template class SimpleVector { private: T *v; int arraySize; public: SimpleVector ( void ) { v = NULL; arraySize = 0; } ; SimpleVector ( int ); SimpleVector ( const SimpleVector & ); ~SimpleVector ( void ); int getSize ( void ) { return arraySize; }; T &operator[] ( const int & ); }; // SimpleVector

Starting Out with C++, 3 rd Edition 47 SimpleVector.cpp – Program template SimpleVector ::SimpleVector ( int s ) { arraySize = s; v = new T [ s ]; assert( v); for ( int i = 0; i < arraySize; i++ ) v[i]= 0; } // SimpleVector::SimpleVector template SimpleVector ::~SimpleVector ( void ) { if ( arraySize > 0 ) delete [] v; } // SimpleVector::~SimpleVector void main() {SimpleVector mine(5); cout << mine.getSize() << endl; }

Starting Out with C++, 3 rd Edition 48 Declaring Objects of Class Templates The declaration of class templates is a little different. Consider the following examples: –SimpleVector intTable ( 10 ); –SimpleVector floatTable ( 10 ); In these, the parameter inside the angle brackets replaces the T in the previous declarations.

Starting Out with C++, 3 rd Edition At your seats Try adding a new function to print out the contents of the simple vector

Starting Out with C++, 3 rd Edition void printAll(void); template void SimpleVector ::printAll(void) { cout << "contents:"; for (int i=0 ;i < arraySize; i++) cout << v[i] << " "; cout << endl; }

Starting Out with C++, 3 rd Edition 51 Class Templates and Inheritance #ifndef SEARCHABLEVECTOR_H #define SEARCHABLEVECTOR_H #include “SimpleVector.h” template class SearchableVector : public SimpleVector { public: SearchableVector ( ) : SimpleVector ( ) { } SearchableVector ( int s ) : SimpleVector ( s ) { } SearchableVector ( SearchableVector & ); int findItem ( T ); }; // SearchableVector