CMSC 202 Lesson 21 Exceptions II.

Slides:



Advertisements
Similar presentations
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.
Advertisements

1 Chapter 17-2 Templates and Exceptions Dale/Weems.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 23 - Exception Handling Outline 23.1Introduction 23.2When Exception Handling Should Be Used 23.3Other.
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.
CSIS 123A Lecture 11 Exception Handling. Introduction  Typical approach to development:  Write programs assuming things go as planned  Get ‘core’ working.
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.
. Plab – Tirgul 10 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
Plab – Tirgul 8 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
CSE333 SECTION 7. Template vs Generics C++ templates are similar to preprocessor macros A template will be “materialized” into multiple copies with T.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 13 - Exception Handling Outline 13.1Introduction 13.2When Exception Handling Should Be Used.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
C++ Memory Overview 4 major memory segments Key differences from Java
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Exceptions and Program Correctness based on the original work by Dr. Roger deBry Version 1.1.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exception Handling Outline 23.1 Introduction
CMSC 202 Lesson 6 Functions II. Warmup Correctly implement a swap function such that the following code will work: int a = 7; int b = 8; Swap(a, b); cout.
CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck.
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.
EE4E. C++ Programming Lecture 6 Advanced Topics. Contents Introduction Introduction Exception handling in C++ Exception handling in C++  An object oriented.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
On dynamic memory and classes ● We previously had only discussed dynamic memory in regards to structs and dynamic arrays. ● However, they can be used (to.
Namespace יום ראשון 13 נובמבר 2016 יום ראשון 13 נובמבר 2016 יום ראשון 13 נובמבר 2016 יום ראשון 13 נובמבר 2016 יום ראשון 13 נובמבר 2016 יום ראשון 13 נובמבר.
Exceptions handling Try, catch blocks Throwing exceptions.
Exception handling.
IS 0020 Program Design and Software Tools
Exceptions Error Handling and Recovery
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
CMSC202 Computer Science II for Majors Lecture 16 – Exceptions
Topics: Templates Exceptions
Pointers and Dynamic Arrays
Jim Fawcett CSE687 – Object Oriented Design Spring 2001
Exceptions David Rabinowitz.
Memory Management with Classes
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Chapter 10 – Exception Handling
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Object-Oriented Programming (OOP) Lecture No. 45
Why exception handling in C++?
C++ Memory Management Idioms
This pointer, Dynamic memory allocation, Constructors and Destructor
Chapter 14: Exception Handling
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 17 Templates and Exceptions Part 2
CMSC 202 Lesson 22 Templates I.
Exceptions 2 CMSC 202.
Advanced C++ Exception Handling
Chapter 15 Pointers, Dynamic Data, and Reference Types
Exceptions 1 CMSC 202.
Exceptions handling Try, catch blocks Throwing exceptions.
Templates I CMSC 202.
CMSC 202 Lesson 6 Functions II.
Pointers and References
Department of Computer and Information Science, School of Science, IUPUI Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI
Lecture 9.
Exceptions for safe programming.
Exceptions.
CMSC 202 Lesson 20 Exceptions 1.
Copy Constructors and Overloaded Assignment
CMSC 202 Lesson 5 Functions I.
Presentation transcript:

CMSC 202 Lesson 21 Exceptions II

Warmup double quotient(int num, int den) { if (den == 0) ________________________________ return static_cast<double>(num) / den; } int main() int numerator, denominator; double result; cout << "Input numerator and denominator" << endl; cin >> numerator >> denominator; try { result = quotient(numerator, denominator); cout << "The quotient is: " << result << endl; catch (____________________) { // exception handler cerr << "Exception occurred: " << _________ << endl; // code continues here return 0; throw string(“Divide by zero”); Complete the following code by throwing a simple string describing the error string& message message

Review Purpose of Exceptions Three Key Components Handle Errors Three Key Components Try Catch Throw Handle Multiple Exceptions? Absolutely

Exception Classes Name? Data? Methods? Reflects error, not code that throws error Data? Basic information or a message Parameter value Name of function that detected error Description of error Methods? Constructor (one or more) Accessor (one or more)

Code that catches this exception gets the parameter name and its value Exception Examples Code that catches this exception gets the parameter name and its value // Good example of an Exception Class class NegativeParameter { public: NegativeParameter( const string& parameter, int value ); int GetValue ( ) const; const string& GetParameter( ) const; private: int m_value; string m_paramName; }; // Trivial example of an Exception Class class MyException { }; Code that catches this exception gets no other information – just the “type” of exception thrown

Exception Specification Functions/Methods can specify which exceptions they throw (or that they don’t throw any) Syntax: // Throws only 1 type of exception retType funcName( params ) throw (exception); // Throws 2 types of exceptions (comma separated list) retType funcName( params ) throw (exception1, exception2); // Promises not to throw any exceptions retType funcName( params ) throw ( ); // Can throw any exceptions [backwards compatibility] retType funcName( params );

Specification Example // Divide() throws only the DivideByZero exception void Divide (int dividend, int divisor ) throw (DivideByZero); // Throws either DivideByZero or AnotherException void Divide (int dividend, int divisor ) throw (DivideByZero, AnotherException); // Promises not to throw any exception void Divide (int dividend, int divisor ) throw ( ); // This function may throw any exception it wants void Divide (int dividend, int divisor );

Exceptions in Constructors Best way to handle Constructor failure Replaces Zombie objects! Any sub-objects that were successfully created are destroyed (destructor is not called!) Example: // MyClass constructor MyClass::MyClass ( int value ) { m_pValue = new int(value); // pretend something bad happened throw NotConstructed( ); }

Exceptions in Destructors Bad, bad idea… What if your object is being destroyed in response to another exception? Should runtime start handling your exception or the previous one? General Rule… Do not throw exceptions in destructor

Standard Library Exceptions #include <stdexcept> bad_alloc Thrown by new when a memory allocation error occurs out_of_range Thrown by vector's at( ) function for an bad index parameter. invalid_argument Thrown when the value of an argument (as in vector< int > intVector(-30);) is invalid Derive from std::exception Define own classes that derive…

Exceptions and Pointers What happens to the Fred object? void myNew1stFunction( ) { // dynamically allocate a Fred object Fred *pFred = new Fred; try { // call some function of Fred } catch( ... ) // for all exceptions throw; // rethrow to higher level // destroy the Fred object // if no exception and normal termination delete pFred;

What’s not so good about this solution? One Solution… What’s not so good about this solution? void myNew1stFunction( ) { // dynamically allocate a Fred object Fred *pFred = new Fred; try { // call some function of Fred } catch( ... ) // for all exceptions delete pFred; // delete the object throw; // rethrow to higher level // destroy the Fred object // if no exception and normal termination delete pFred; Duplicated Code!

Better Solution auto_ptr Control can be passed… A kind of “smart pointer” Takes ownership of dynamic memory Frees memory when pointer is destroyed #include <memory> Control can be passed… Between auto_ptrs and other auto_ptrs Only one auto_ptr can own an object at a time Between auto_ptrs and normal pointers

Auto_ptr Example #include <memory> void my2ndFunction( ) { Fred* p1 = new Fred; // p1 "owns" the Fred object auto_ptr<Fred> p2( p1 ); // pass ownership to an auto_ptr // use the auto_ptr the same way // we'd use a regular pointer *p2 = someOtherFred; // same as "*p1 = someOtherFred;" p2->SomeFredFunction(); // same as "p1->SomeFredFunction();" // use release() to take back ownership Fred* p3 = p2.release(); // now p3 "owns" the Fred object delete p3; // need to manually delete the Fred // p2 doesn't own any Fred object, and so won't try // to delete one }

Multiple Auto_ptrs void my3rdFunction() { auto_ptr<Fred> p1( new Fred ); auto_ptr<Fred> p2; p1->SomeFredFunction( ); // OK p2 = p1; // p2 owns Fred object and p1 does not p2->SomeFredFunction( ); // OK // watch for this pitfall p1->SomeFredFunction( ); // error! p1 is a null pointer // when p1 and p2 go out of scope // p2's destructor deletes the Fred object // p1's destructor does nothing }

Exception-Safe Code Fundamentals Exception-safe code Hard to do well Leaves the object (or program) in a consistent and valid state Hard to do well Think through even simple code thoroughly…

Exception-UNsafe Example // unsafe assignment operator implementation FredArray& FredArray::operator=( const FredArray& rhs) { if ( this != &rhs ) // free existing Freds delete [] m_data; // 1 // now make a deep copy of the right-hand object m_size = rhs.m_size; // 2 m_data = new Fred [ m_size ]; // 3 for (int j = 0; j < m_size; j++ ) // 4 m_data[ j ] = rhs.m_data [ j ]; // 5 } return *this;

Exception-safe Example // Better assignment operator implementation FredArray& FredArray::operator=( const FredArray& rhs) { if ( this != &rhs ) // code that may throw an exception first // make a local temporary deep copy Fred *tempArray = new Fred[rhs.m_size]; for ( int j = 0; j < rhs.m_size; j++ ) tempArray[ j ] = rhs.m_data [ j ]; // now code that does not throw exceptions delete [] m_data; m_size = rhs.m_size; m_data = tempArray; } return *this; Rule of Thumb: Do any work that may throw an exception off “to the side” using local variables THEN change the object’s state using methods that DON’T throw exceptions How could we improve this?

Exception Guarantees Each function/method can guarantee one of the following when an exception occurs: Weak Guarantee Program/Object will not be corrupt No memory is leaked Object is usable, destructible Strong Guarantee Function has no effect Program/Object state is same as before NoThrow Guarantee Function ensures no exceptions will be thrown Usually: destructors, delete and delete[ ] Which should you follow? C++ library: A function should always support the strictest guarantee that it can support without penalizing users who don't need it Great test question! Hint, hint!

Challenge Assume that our Board constructor throws an exception if the file is not properly formatted Insufficient rows and columns Extra rows or columns Unknown character in Board file Etc. Use an Exception-safe strategy for building the board