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,

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Data Structures Using C++ 2E
TEMPLATES Lecture Presented By SHERY KHAN Object Orienting Programming.
Chapter 7: User-Defined Functions II
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
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.
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
CS Advanced C++ Exception Handling Topic #5.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 8 Arrays and Strings
 2006 Pearson Education, Inc. All rights reserved Generics.
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.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  Due to poor understanding of the problem and solution.
Templates & STL 1.Generic Programming 2.C++ Templates 3.Function Templates 4.Class Templates 5.Standard Template Library (STL) 6.Vectors 7.Iterators 1.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Data Structures Using C++ 2E
Chapter 8 Arrays and Strings
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 6: User-Defined Functions
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 16: Exceptions,
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
Overview of C++ Templates
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
LECTURE LECTURE 14 Exception Handling Textbook p
Chapter 3: User-Defined Functions I
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Exception Handling How to handle the runtime errors.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Exception Handling C++.
Chapter 6: User-Defined Functions I
C++ Templates.
Exceptions, Templates, and the Standard Template Library (STL)
Exceptions, Templates, and the Standard Template Library (STL)
Why exception handling in C++?
Starting Out with C++ Early Objects Eighth Edition
User-Defined Functions
Chapter 14: Exception Handling
Topics Introduction to File Input and Output
Exceptions and Templates
Exception Handling.
Standard Version of Starting Out with C++, 4th Edition
Chapter 6: User-Defined Functions I
Exceptions, Templates, and the Standard Template Library (STL)
Topics Introduction to File Input and Output
Presentation transcript:

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, and the Standard Template Library (STL)

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 2 Topics 16.1 Exceptions 16.2 Function Templates 16.3 Class Templates 16.4 Class Templates and Inheritance 16.5 Introduction to the Standard Template Library

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide Exceptions An exception is a condition that occurs at execution time and makes normal continuation of the program impossible When an exception occurs, the program must either terminate or jump to special code for handling the exception. The special code for handling the exception is called an exception handler

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 4 Exceptions – Key Words throw – followed by an argument, is used to throw an exception try – followed by a block { }, is used to invoke code that throws an exception catch – followed by a block { }, is used to process exceptions thrown in preceding try block. Takes a parameter that matches the type thrown.

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 5 Throwing an Exception Code that detects the exception must pass information to the exception handler. This is done using a throw statement: throw "Emergency!" throw 12; In C++, information thrown by the throw statement may be a value of any type

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 6 Catching an Exception Block of code that handles the exception is said to catch the exception and is called an exception handler An exception handler is written to catch exceptions of a given type: For example, the code catch(char *str) { cout << str; } can only catch exceptions of C-string type

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 7 Catching an Exception Another example of a handler: catch(int x) { cerr << "Error: " << x; } This can catch exceptions of type int

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 8 Connecting to the Handler Every catch block is attached to a try block of code and is responsible for handling exceptions thrown from that block try { } catch(char e1) { // This code handles exceptions // of type char that are thrown // in this block }

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 9 Handling Multiple Exceptions Multiple catch blocks can be attached to the same block of code. The catch blocks should handle exceptions of different types try{...} catch(int iEx){ } catch(char *strEx){ } catch(double dEx){ }

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 10 Throwing an Exception Class An exception class can be defined and thrown Catch block must be designed to catch an object of the exception class Exception class object can pass data to exception handler via data members

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 11 Nested Exception Handling Try blocks can be nested in other try blocks and even in catch blocks try { try{ } catch(int i){ } } catch(char *s) { }

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 12 Execution of Catch Blocks The catch block syntax is similar to a that of a function Catch block has a formal parameter that is initialized to the value of the thrown exception before the block is executed

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 13 Example An example of exception handling is code that computes the square root of a number. It throws an exception in the form of a C-string if the user enters a negative number

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 14 Example int main( ) { try { double x; cout << "Enter a number: "; cin >> x; if (x < 0) throw "Bad argument!"; cout << "Square root of " << x << " is " << sqrt(x); } catch(char *str) { cout << str; } return 0; }

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 15 Flow of Control 1.Computer encounters a throw statement in a try block 2.The computer evaluates the throw expression, and immediately exits the try block 3.The computer selects an attached catch block that matches the type of the thrown value, places the value in the catch block’s formal parameter, and executes the catch block

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 16 When There is no Handler If the compiler cannot find a matching handler: –The compiler looks for a suitable handler attached to an enclosing try block in the same function –If there is no matching handler in the function, it terminates execution of the function, and continues the search for a handler at the point of the call in the calling function.

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 17 Unwinding the Stack An unhandled exception propagates backwards into the calling function and appears to be thrown at the point of the call The computer will keep terminating function calls and tracing backwards along the call chain until it finds an enclosing try block with a matching handler, or until the exception propagates out of main (terminating the program). This process is called unwinding the call stack

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide Function Templates Function template: A pattern for creating definitions of functions that differ only in the type of data they manipulate Templates are used to achieve generic programming: the writing of code that can be instantiated and made to work for different types

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 19 Example Two functions that differ only in the type of the data they manipulate void swap(int &x, int &y) { int temp = x; x = y; y = temp; } void swap(char &x, char &y) { char temp = x; x = y; y = temp; }

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 20 A swap Template The logic of both functions can be captured with one template function definition template void swap(T &x, T &y) { T temp = x; x = y; y = temp; }

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 21 Using a Template Function When a function defined by a template is called, the compiler creates the actual definition from the template by inferring the type of the type parameters from the arguments in the call: int i = 1, j = 2; swap(i,j); makes compiler instantiate the template with type int in place of the type parameter T

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 22 Function Template Notes A function template is a pattern No actual code is generated until the function named in the template is called A function template uses no memory When passing a class object to a function template, ensure that all operators referred to in the template are defined or overloaded in the class definition

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 23 Function Template Notes All data types specified in template prefix must be used in template definition Function calls must pass parameters for all data types specified in the template prefix Function templates can be overloaded – need different parameter lists Like regular functions, function templates must be defined before being called

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 24 Where to Start When Defining Templates Templates are often appropriate for multiple functions that perform the same task with different parameter data types Develop function using usual data types first, then convert to a template: –add template prefix –convert data type names in the function to a type parameter (i.e., a T type) in the template

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide Class Templates It is possible to define templates for classes. Unlike functions, a class template is instantiated by supplying the type name ( int, float, string, etc.) at object definition

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 26 Class Template Consider the following classes 1.Class used to join two integers by adding them: class Joiner { public: int combine(int x, int y) {return x + y;} }; 2.Class used to join two strings by concatenating them: class Joiner { public: string combine(string x, string y) {return x + y;} };

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 27 Example class Template A single class template can capture the logic of both classes: it is written with a template prefix that specifies the data type parameters: template class Joiner { public: T combine(T x, T y) {return x + y;} };

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 28 Using Class Templates To create an object of a class defined by a template, specify the actual parameters for the formal data types Joiner jd; Joiner sd; cout << jd.combine(3.0, 5.0); cout << sd.combine("Ha", "Ho"); Prints 8.0 and HaHo

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide Class Templates and Inheritance Templates can be combined with inheritance You can derive –Non template classes from a template class: instantiate the base class template and then inherit from it –Template class from a template class Other combinations possible

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide Introduction to the Standard Template Library Standard Template Library (STL): a library containing templates for frequently used data structures and algorithms STL is not supported by older compilers

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 31 Standard Template Library Two important types of data structures in the STL: –containers: classes that store data and impose some organization on it –iterators: like pointers; mechanisms for accessing elements in a container

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 32 Containers Two types of container classes in STL: –sequence containers: organize and access data sequentially, as in an array. These include vector, dequeue, and list –associative containers: use keys to allow data elements to be quickly accessed. These include set, multiset, map, and multimap

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 33 Creating Container Objects For example, to create a list of int, write list mylist; To create a vector of string objects, write vector myvector;

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 34 Iterators Generalization of pointers, used to access information in containers Four types: –forward (uses ++ ) –bidirectional (uses ++ and -- ) –random-access –input (can be used with cin and istream objects) –output (can be used with cout and ostream objects)

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 35 Algorithms STL contains algorithms implemented as function templates to perform operations on containers. Requires algorithm header file Collection of algorithms includes binary_searchcount for_eachfind find_ifmax_element min_elementrandom_shuffle sort and others

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 36 Containers and Iterators Each container class defines an iterator type, used to access its contents The type of an iterator is determined by the type of the container: list ::iterator x; list ::iterator y; x is an iterator for a container of type list

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 37 Containers and Iterators Each container class defines functions that return iterators: begin(): returns iterator to item at start end(): returns iterator denoting end of container

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 38 Containers and Iterators Iterators support pointer-like operations: if iter is an iterator: –*iter is the item it points to: this dereferences the iterator –iter++ advances to the next item in the container –iter-- backs up in the container The end() iterator points to past the end: it should never be dereferenced

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 39 Traversing a Container Given a vector vector v; for (int k=1; k<= 5; k++) v.push_back(k*k); Traverse it using iterators: vector ::iterator iter = v.begin(); while (iter != v.end()) { cout << *iter << " "; iter++} Prints

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 40 Using STL algorithms Many STL algorithms manipulate portions of STL containers specified by a begin and end iterator max_element(iter1, iter2) finds max element in the portion of a container delimited by iter1, iter2 min_element(iter1, iter2) is similar to above

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 41 More STL algorithms random_shuffle(iter1, iter2) randomly reorders the portion of the container in the given range sort(iter1, iter2) sorts the portion of the container specified by the given range

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 42 random-shuffle Example The following example stores the squares 1, 4, 9, 16, 25 in a vector, shuffles the vector, and then prints it out

© 2006 Pearson Education. All Rights Reserved Chapter 16 Starting Out with C++: Early Objects 5/e slide 43 random_shuffle example int main() { vector vec; for (int k = 1; k <= 5; k++) vec.push_back(k*k); random_shuffle(vec.begin(),vec.end()); vector ::iterator p = vec.begin(); while (p != vec.end()) { cout << *p << " "; p++; } return 0; }

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, and the Standard Template Library (STL)