1 Chapter 17-2 Templates and Exceptions Dale/Weems.

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
Lecture 9. 2 Exception  An exception is a unusual, often unpredictable event, detectable by software or hardware, that requires special processing occurring.
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.
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.
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.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Exception Handling: A Deeper.
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.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  due to poor understanding of the problem and solution.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
Rossella Lau Lecture 9, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 9: Application with Exception Handling 
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Introduction to C++ Templates and Exceptions l C++ Function Templates l C++ Class Templates l Exception and Exception Handler.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
Object Oriented Programming
Handling ErrorstMyn1 Handling Errors Up to this point we haven't worried much about errors or exceptions. First, let's distinguish between errors and exceptions.
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.
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  Due to poor understanding of the problem and solution.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
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 –
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
HANDLING EXCEPTIONS Chapter 9. Outline  Learn about the limitations of traditional error-handling methods  Throw exceptions  Use try blocks  Catch.
ICS 313: Programming Language Theory Chapter 14: Exceptions.
CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II.
1 An Exception is… An unusual, often unpredictable event, detectable by software or hardware, that requires special processing An exception handler is.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exception Handling Outline 23.1 Introduction
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
LECTURE LECTURE 14 Exception Handling Textbook p
1 Chapter 17 Templates and Exceptions Dale/Weems.
1 Chapter 17 Templates and Exceptions Dale/Weems/Headington.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Exception Handling How to handle the runtime errors.
Introduction to C++ Templates and Exceptions C++ Function Templates C++ Class Templates Exception and Exception Handler.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 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.
Exception handling.
Exceptions Error Handling and Recovery
CS212: Object Oriented Analysis and Design
Why exception handling in C++?
Part IX Fundamentals of C and C++ Programming Exception Handling
EXCEPTION HANDLING.
Chapter 14: Exception Handling
Exceptions with Functions
Chapter 17 Templates and Exceptions Part 2
Exception Handling Chapter 9 Edited by JJ.
Exception Handling.
Exceptions 1 CMSC 202.
Object-Oriented Programming (OOP) Lecture No. 43
Object-Oriented Programming (OOP) Lecture No. 44
Lecture 9.
Exceptions for safe programming.
CMSC 202 Lesson 20 Exceptions 1.
More C++ Concepts Exception Handling Templates.
Presentation transcript:

1 Chapter 17-2 Templates and Exceptions Dale/Weems

2 An Exception is… An exception is an unusual, often unpredictable event, detectable by software or hardware, that requires special processing; also, in C++, a variable or class object that represents an exceptional event An exception handler is a section of program code that is executed when a particular exception occurs

3 The throw Statement Throw: to signal the fact that an exception has occurred; also called raise ThrowStatement throw Expression

4 Throw examples (1) l throw 5; l string str = “Invalid customer age”; throw str; l class SalaryError {}; … SalaryError sal; throw sal;

5 Throw examples (2) l Use of anonymous (unnamed) object class SalaryError {}; … throw SalaryError(); l A wrong way throw SalaryError;

6 The try-catch Statement try Block catch (FormalParameter) Block catch (FormalParameter) TryCatchStatement How one part of the program catches and processes the exception that another part of the program throws. FormalParameter DataType VariableName …

7 Example of a try-catch Statement try { // Statements that process personnel data and may throw // exceptions of type int, string, and SalaryError } catch (int) { // Statements to handle an int exception }

8 try-catch Continued catch (string s) { cout << s << endl; // Prints "Invalid customer age" // More statements to handle an age error } catch (SalaryError) { // Statements to handle a salary error }

9 Execution of try-catch No statements throw an exception Statement following entire try-catch statement A statement throws an exception Exception Handler Statements to deal with exception are executed Control moves directly to exception handler

10 Selecting an Exception Handler The computer Examines data types of the formal parameters in exception handlers Searches in a “north-to-south” order Selects first formal parameter whose data type matches that of the thrown exception Ellipse parameters are a “wild card” and catch all (Place the “catch all” handler last)

11 More on Selecting Exception Handlers The parameter’s name is needed only if statements in the body of the exception handler use that variable It is a good idea to use only  user-defined classes (and structs) as exception types  one type per exception  descriptive identifiers

12 An example class SalaryError// Exception class {}; class BadRange// Exception class {}; … if ( condition ) throw SalaryError(); … if ( condition ) throw BadRange();

13 Nonlocal Exception Handlers It is more common for the throw to occur inside a function that is called from within a try- clause than for the throw to be located within the try-catch statement

14 Throwing an Exception to be Caught by the Calling Code void Func4() { if (error) throw ErrType(); } Normal return void Func3() { try { Func4(); } catch (ErrType) { } } Function call Return from thrown exception

15 No ErrType handler ErrType handler No ErrType handler throw ErrType(); Cal l Immediate return Immediate return Immediate return Func1 No ErrType handler throw ErrType(); Call Immediate return Immediate return Immediate return Program terminates immediately Func2 Func3 Func4 main Immediate return Function Func1 has a handler for ErrTypeNo function has a handler for ErrType Func1 Func2 Func3 Func4 Passing an Exception up the Chain of Function Calls

16 Re-Throwing an Exception l The throw expression is optional throw; l Re-throwing an exception in C++ allows partial exception handling

17 An example (1) void WriteToFile( parameters ) { … // Open a file for output try { while ( condition ) { DoSomething( arguments ); // May throw a BadData exception … // Write to output file }

18 An example (2) catch ( BadData ) { …// Write massage to output file and // close it throw;// Re-throw the exception } …// Continue processing // and close the output file }

19 Standard Exceptions l Exceptions Thrown by the Language  new, dynamic_cast, typeid, exception specification l Exceptions Thrown by Standard Library Routines  Facilities inherited from the C language  Facilities designed specifically for C++

20 Exception thrown by new float* arr; try { arr = new float[50000]; } catch ( bad_alloc ) { cout << “*** Out of memory. Can’t allocate array.” << endl; return 1;// Terminate the program } …// Continue. Allocation succeeded

21 C library routine set errno l Simulate throwing exceptions from C library routines class CLibErr// Our own exception class {}; … void SomeFunc( parameters ) { … errno = 0; C_lib_routine( arguments ); if (errno != 0) throw CLibErr(); … }

22 Exceptions thrown by C++ libraries (1) Exceptions thrown by string classes void SomeFunc( parameters ) { string s1, s2; try { … s2 = s1.substr(pos, len); // May throw out_of_range() s1 = s1 + s1 + s2; // May throw length_error() … }

23 Exceptions thrown by C++ libraries (2) Exceptions thrown by string classes catch ( out_of_range ) { cout << “Exception: out_of_range in SomeFunc” << endl; throw;// Re-throw exception to a caller } catch ( length_error ) { cout << “Exception: length_error in SomeFunc” << endl; throw; // Re-throw exception to a caller } …// Continue if no errors }

24 Dividing by ZERO Apply what you know: int Quotient(/* in */ int numer, // The numerator /* in */ int denom) // The denominator { if (denom != 0) return numer / denom; else // What to do?? }

25 A Solution // “quotient.cpp” -- Quotient program #include #include using namespace std; int Quotient(int, int); class DivByZero // Exception class {}; int main() { int numer; // Numerator int denom; // Denominator cout << "Enter numerator and denominator: ";

26 cin >> numer >> denom; while (cin) { try { cout << "Their quotient: " << Quotient(numer, denom) << endl; } catch (DivByZero) { cout << "*** Denominator can't be 0" << endl; } cout << "Enter numerator and denominator: "; cin >> numer >> denom; } return 0; }

27 int Quotient(/* in */ int numer, // The numerator /* in */ int denom) // The denominator { if (denom == 0) throw DivByZero(); return numer / denom; }

28 Appointment Calendar l Replace array-based list with linked list to demonstrate that changing implementation doesn’t change client code l Add exceptions to Appointment Calendar Program

29 The End of Chapter 17 Part 2