Chapter 17 Templates and Exceptions Part 2

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

Chapter 16 Exception Handling. What is Exception Handling? A method of handling errors that informs the user of the problem and prevents the program from.
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.
1 Chapter 17-2 Templates and Exceptions Dale/Weems.
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.
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.
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 Programming Techniques Course Version 1.0.
Introduction to C++ Templates and Exceptions l C++ Function Templates l C++ Class Templates l Exception and Exception Handler.
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.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
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.
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.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
C ++ MULTIPLE CHOICE QUESTION
Exception handling.
Exception Handling C++.
C++ Exceptions.
Exceptions Error Handling and Recovery
Chapter 16 Exception Handling
Abstract Class Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes are used to provide an Interface for.
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
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.
CS212: Object Oriented Analysis and Design
Topics: Templates Exceptions
Jim Fawcett CSE687 – Object Oriented Design Spring 2001
Andy Wang Object Oriented Programming in C++ COP 3330
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Why exception handling in C++?
Part IX Fundamentals of C and C++ Programming Exception Handling
EXCEPTION HANDLING.
Object Oriented Programming COP3330 / CGS5409
Exceptions C++ Interlude 3
Chapter 14: Exception Handling
Exception Handling Chapter 9.
Exceptions with Functions
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 12 Exception Handling and Text IO
Exception Handling Chapter 9 Edited by JJ.
Exception Handling In Text: Chapter 14.
Exceptions CSCE 121 J. Michael Moore
Exception Handling.
Exceptions 1 CMSC 202.
Python Syntax Errors and Exceptions
Object-Oriented Programming (OOP) Lecture No. 43
Exception and Event Handling
Object-Oriented Programming (OOP) Lecture No. 44
Department of Computer and Information Science, School of Science, IUPUI Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI
Lecture 9.
Exceptions for safe programming.
CMSC 202 Lesson 20 Exceptions 1.
More C++ Concepts Exception Handling Templates.
Presentation transcript:

Chapter 17 Templates and Exceptions Part 2 Dale/Weems/Headington

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.

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

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

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

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

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

try-catch Continued // call all other types of exceptions cout << s << endl; // Prints "Invalid customer age" // More statements to handle an age error } catch ( SalaryError ) { // Statements to handle a salary error catch (…) // call all other types of exceptions

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

Selecting an Exception Handler The computer: matches data types of throw clause with the data types in the catch clauses Searches in a “north-to-south” order Selects first handler whose data type matches that of the thrown exception Ellipse parameters are a “wild card” and catch all. Place the “catch all” handler last.

Selecting an Exception Handler What constitutes a match? Suppose an object of type T is thrown. A catch block that takes an argument of type C is a match if: T and C are the same type. C adds a reference qualifies (e.g. int can be caught by int&) C is a base class of publicly derived class T Note: matching process more restrictive than for function calls. Ex: int can’t be caught by float or char

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

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

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

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

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

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

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 }

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

A Solution // quotient.cpp -- Quotient program   #include<iostream> #include <string> using namespace std; int Quotient( int, int ); class DivByZero // Exception class {}; int main() { int numer; // Numerator int denom; // Denominator

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

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

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

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; // return to calling function … // Continue. Allocation succeeded

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() }

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” throw; // Re-throw exception to a caller … // Continue if no errors

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?? }

The end of Chapter 17 Part 2