Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.

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

Topics Introduction Types of Errors Exceptions Exception Handling
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
C/c++ 4 Yeting Ge.
C++ is Fun – Part 11 at Turbine/Warner Bros.! Russell Hanson.
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.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Exceptions, Templates, and the Standard Template Library (STL)
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
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,
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
 2006 Pearson Education, Inc. All rights reserved Generics.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
1 Chapter Eight Exception Handling. 2 Objectives Learn about exceptions and the Exception class How to purposely generate a SystemException Learn about.
1 CSC241: Object Oriented Programming Lecture No 27.
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  Due to poor understanding of the problem and solution.
Data Structures Using C++ 2E
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Operator Overloading & Exception Handling TCP1201 OOPDS 1 Lecture 5 1.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 16: Exceptions,
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 23 - Exception Handling Outline 23.1Introduction.
Exception Handling Outline 23.1 Introduction
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Chapter 6 - More About Problem Domain Classes1 Chapter 6 More About Problem Domain Classes.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
1 ENERGY 211 / CME 211 Lecture 7 October 6, 2008.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
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.
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 Error Handling and Recovery
C++ Templates.
Exceptions, Templates, and the Standard Template Library (STL)
Exceptions, Templates, and the Standard Template Library (STL)
Why exception handling in C++?
Part IX Fundamentals of C and C++ Programming Exception Handling
Starting Out with C++ Early Objects Eighth Edition
Chapter 14: Exception Handling
Exceptions and Templates
Chapter 3: Input/Output
Exception Handling.
Exceptions 1 CMSC 202.
Standard Version of Starting Out with C++, 4th Edition
Exceptions, Templates, and the Standard Template Library (STL)
COP 3330 Object-oriented Programming in C++
CMSC 202 Exceptions.
CMSC 202 Lesson 20 Exceptions 1.
Presentation transcript:

Exceptions, Templates, And The Standard Template Library (STL) Chapter 16

Exceptions Indicate that something unexpected has occurred or been detected Allow program to deal with the problem in a controlled manner Can be as simple or complex as program design requires

3 Exceptions - Terminology Exception: object or value that signals an error Throw an exception: send a signal that an error has occurred Catch/Handle an exception: process the exception; interpret the signal

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 detect and process exceptions thrown in preceding try block. Takes a parameter that matches the type thrown.

5 Exceptions – Flow Of Control 1)A function that throws an exception is called from within a try block 2)If the function throws an exception, the function terminates and the try block is immediately exited. A catch block to process the exception is searched for in the source code immediately following the try block. 3)If a catch block is found that matches the exception thrown, it is executed. If no catch block that matches the exception is found, the program terminates.

6 Exceptions – Example (1) // function that throws an exception int totalDays(int days, int weeks) { if ((days 7)) throw "invalid number of days"; // the argument to throw is the // character string else return (7 * weeks + days); }

7 Exceptions – Example (2) try // block that calls function { totDays = totalDays(days, weeks); cout << "Total days: " << days; } catch (char *msg) // interpret // exception { cout << "Error: " << msg; }

8 Exceptions – What Happens 1) try block is entered. totalDays function is called 2)If 1st parameter is between 0 and 7, total number of days is returned and catch block is skipped over (no exception thrown) 3)If exception is thrown, function and try block are exited, catch blocks are scanned for 1 st one that matches the data type of the thrown exception. catch block executes

9 Exceptions - Notes Predefined functions such as new may throw exceptions The value that is thrown does not need to be used in catch block. –in this case, no name is needed in catch parameter definition –catch block parameter definition does need the type of exception being caught

10 Exception Not Caught? An exception will not be caught if –it is thrown from outside of a try block –there is no catch block that matches the data type of the thrown exception If an exception is not caught, the program will terminate

11 Exceptions And Objects An exception class can be defined in a class and thrown as an exception by a member function An exception class may have: –no members: used only to signal an error –members: pass error data to catch block A class can have > 1 exception class

12 Exceptions – What Happens After catch Block? Once an exception is thrown, the program cannot return to throw point. The function executing throw terminates (does not return), other calling functions in try block terminate, resulting in unwinding the stack If objects were created in the try block and an exception is thrown, they are destroyed.

13 Nested try Blocks try/catch blocks can occur within an enclosing try block Exceptions caught at an inner level can be passed up to a catch block at an outer level: catch ( ) {... throw; // pass exception up } // to next level

Function Templates Function template: a pattern for a function that can work with many data types When written, parameters are left for the data types When called, compiler generates code for specific data types in function call

15 Function Template Example template T times10(T num) { return 10 * num; } template prefix generic data type type parameter What gets generated when times10 is called with an int: What gets generated when times10 is called with a float: int times10(int num) { return 10 * num; } float times10(float num) { return 10 * num; }

16 Function Template Example template T times10(T num) { return 10 * num; } Call a template function in the usual manner: int ival = 3; float fval = 2.55; cout << times10(ival); // displays 30 cout << times10(fval); // displays 25.5

17 Function Template Notes Can define a template to use multiple data types: template Example: template // T1 and T2 will be double mpg(T1 miles, T2 gallons) // replaced in the { // called function return miles / gallons // with the data } // types of the // arguments

18 Function Template Notes Function templates can be overloaded Each template must have a unique parameter list template T sumAll(T num)... template T1 sumall(T1 num1, T2 num2)...

19 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 Like regular functions, function templates must be defined before being called

20 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 in the template are defined or overloaded in the class definition

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

Class Templates Classes can also be represented by templates. When a class object is created, type information is supplied to define the type of data members of the class. Unlike functions, classes are instantiated by supplying the type name ( int, float, string, etc.) at object definition

23 Class Template Example template class grade { private: T score; public: grade(T); void setGrade(T); T getGrade() };

24 Class Template Example Pass type information to class template when defining objects: grade testList[20]; grade quizList[20]; Use as ordinary objects once defined

25 Class Templates And Inheritance Class templates can inherit from other class templates: template class Rectangle {... }; template class Square : public Rectangle {... }; Must use type parameter T everywhere base class name is used in derived class

Introduction To The Standard Template Library Standard Template Library (STL): a library containing templates for frequently used data structures and algorithms Not supported by many older compilers

27 Standard Template Library Two important types of data structures in the STL: –containers: classes that stores data and imposes some organization on it –iterators: like pointers; mechanisms for accessing elements in a container

28 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

29 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)

30 Algorithms STL contains algorithms implemented as function templates to perform operations on containers. Requires algorithm header file algorithm includes binary_searchcount for_eachfind find_ifmax_element min_elementrandom_shuffle sort and others