G52CPP C++ Programming Lecture 16

Similar documents
G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 20

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

TEMPLATES AND EXCEPTION HANDLING

05-01 Discussion Notes

G52CPP C++ Programming Lecture 10. Dr Jason Atkin

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

G52CPP C++ Programming Lecture 17

CPSC 427: Object-Oriented Programming

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Midterm Review. PIC 10B Spring 2018

G52CPP C++ Programming Lecture 15

Homework 4. Any questions?

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

IS 0020 Program Design and Software Tools

Programming in C++: Assignment Week 8

COMP6771 Advanced C++ Programming

CPSC 427: Object-Oriented Programming

Laboratorio di Tecnologie dell'informazione

Pointers. Developed By Ms. K.M.Sanghavi

G52CPP C++ Programming Lecture 12

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

CSE 303: Concepts and Tools for Software Development

RAII and Smart Pointers. Ali Malik

CPSC 427: Object-Oriented Programming

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

COMP 2355 Introduction to Systems Programming

CS93SI Handout 04 Spring 2006 Apr Review Answers

The University of Nottingham

C++ Primer for CS175

Chapter 17 vector and Free Store. Bjarne Stroustrup

Fast Introduction to Object Oriented Programming and C++

Lecture 2, September 4

377 Student Guide to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Contents. Error Handling Strategies (cont d) Error handling strategies: error code, assert(), throw-try-catch

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

CS3157: Advanced Programming. Outline

Constructor - example

G52CPP C++ Programming Lecture 18

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

Written by John Bell for CS 342, Spring 2018

G52CPP C++ Programming Lecture 9

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Assertions and Exceptions

CS11 Advanced C++ Fall Lecture 3

Object-Oriented Programming for Scientific Computing

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Traditional Error Handling

COMP6771 Advanced C++ Programming

C++ Crash Kurs. Exceptions. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

C and C++ 7. Exceptions Templates. Alan Mycroft

Exception Safe Coding

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Introduction to Programming using C++

Exceptions, Case Study-Exception handling in C++.

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures

CS2141 Software Development using C/C++ C++ Basics

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Object-Oriented Principles and Practice / C++

Assumptions. History

! Errors can be dealt with at place error occurs

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Object-Oriented Programming (OOP) Fundamental Principles of OOP

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

VALLIAMMAI ENGINEERING COLLEGE

Chapter 17 vector and Free Store

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

A brief introduction to C++

A Tour of the C++ Programming Language

Intermediate Programming, Spring 2017*


C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

Chapter 17 vector and Free Store

A Tour of the C++ Programming Language

COM S 213 PRELIM EXAMINATION #2 April 26, 2001

Short Notes of CS201

Bruce Merry. IOI Training Dec 2013

Assignment 1: SmartPointer

Pointers, Dynamic Data, and Reference Types

CS201 - Introduction to Programming Glossary By

CS24 Week 3 Lecture 1

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Programming in C++: Assignment Week 8

CPSC 427: Object-Oriented Programming

Vector and Free Store (Pointers and Memory Allocation)

AN OVERVIEW OF C++ 1

Object Oriented Programming

CSE 333 Lecture smart pointers

Lecture 8. Exceptions, Constructor, Templates TDDD86: DALP. Content. Contents Exceptions

Recharge (int, int, int); //constructor declared void disply();

Digging into the GAT API

Polymorphism Part 1 1

Advanced Programming

Transcription:

G52CPP C++ Programming Lecture 16 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1

Last Lecture Casting static cast dynamic cast const cast reinterpret cast Implicit type conversion 2

How do we report errors? 1. Return an error value from function Remember to check return value on each call Must have a valid error return value How do we propagate the error? (return again?) 2. Set a global error code Again, have to remember to check it after each call 3. Throw an exception (to report error) Requires an exception handling mechanism This lecture 3

Exceptions Exceptions are thrown to report exceptional circumstances Similar to being able to return an error value of whatever type is desired You can throw any type of object, fundamental type or pointer as an exception in C++ These are different things (pointers!= objects) The standard class library provides some standard exception types, all derived from exception class It is good practice to throw objects which are of sub-classes of exception rather than arbitrary types You add handler code to catch the exception The stack frame is unwound, one function at a time (as if the functions returned immediately) until a catch which matches the type thrown is found Like returning from the functions Same problems/effects as returning from a function 4

Catching exceptions First specify that you want to check for exceptions (try) Then call the code which will may raise the exceptions Then specify which exceptions you will catch, and what to do (this can include re-throwing them) Use throw without arguments in a catch clause to rethrow them try Assume that foo() throws an exception foo(); e.g. throw 1; or MyException ob; throw ob; catch ( int& i ) cout << "int was thrown by foo()" << endl; catch ( ) cout << "Any other exception was thrown" << endl; 5

The catch clause A catch clause will match an exception of the specified type catch clauses are checked in the order in which they are encountered The order of the catch clauses matters! Pointers and objects are different Exceptions are thrown by value Catch by reference or by value would work Catch by reference avoids the copy chars, shorts, ints (etc) are different things catch (... ) will match ANY exception 6

Exception thrown by new void foo() while ( true ) new int[10000]; cout << '.'; int main() try foo(); catch ( bad_alloc ) Loop forever until it fails If memory allocation fails, an exception of type bad_alloc is thrown Catching this exception potentially allows handling the out of memory problem, e.g. save and exit cout << "bad_alloc exception thrown" << endl; catch (... ) cout << Other exception thrown " << endl; 7

Multiple functions #include <iostream> using namespace std; void bar2() switch( rand() % 3 ) case 0: throw 1.2f; case 1: throw "string"; case 2: throw new string("string"); bar2() throws an exception of a random type void bar() try bar2(); catch( float f ) cout << "float" << endl; void foo() try bar(); catch( const char* sz ) cout << "char*" << endl; int main() for ( int i=0 ; i<20 ; i++ ) try foo(); catch(... ) cout << "Other" << endl; 8

The catch clause and sub-classes Sub-class objects ARE base class objects Because inheritance models the is-a relationship catch clauses will match sub-class objects e.g.: catch ( BaseClass& b ) will also catch sub-class objects catch ( BaseClass* b ) will also catch sub-class pointers Reminder: Pointers and objects are different First catch will NOT catch thrown pointers Second catch will NOT catch thrown objects 9

Catching Base class objects struct Base virtual void temp() ; struct Sub1 : public Base void temp() ; struct Sub2 : public Base void temp() ; Base class object is thrown Which catch clause will be used? int test1() try Base b; throw b; A B C D catch ( Sub1& b ) cout << "Sub1" << endl; catch ( Base& b ) cout << Base" << endl; catch ( Sub2& b ) cout << "Sub2" << endl; catch (... ) cout << "Other" << endl; 10

Answer B Check catches in order: It is NOT a Sub1 It is a Base 11

Catching Sub1 class objects struct Base virtual void temp() ; struct Sub1 : public Base void temp() ; struct Sub2 : public Base void temp() ; Sub-class Sub1 object is thrown Which catch clause will be used? int test1() try Sub1 s1; throw s1; A B C D catch ( Sub1& b ) cout << "Sub1" << endl; catch ( Base& b ) cout << Base" << endl; catch ( Sub2& b ) cout << "Sub2" << endl; catch (... ) cout << "Other" << endl; 12

Answer A Check catches in order: It is a Sub1 13

Catching Sub2 class objects struct Base virtual void temp() ; struct Sub1 : public Base void temp() ; struct Sub2 : public Base void temp() ; Sub-class Sub2 object is thrown Which catch clause will be used? int test1() try Sub2 s2; throw s2; A B C D catch ( Sub1& b ) cout << "Sub1" << endl; catch ( Base& b ) cout << Base" << endl; catch ( Sub2& b ) cout << "Sub2" << endl; catch (... ) cout << "Other" << endl; 14

Answer B Check catches in order: It is not a Sub1 It is a Base (Sub2 objects are Base objects) Note: The order here matters It gets caught by the Base catch before it gets to the Sub2 catch The compiler may give you a warning here about the sub-class type exception being caught by the base class catch gcc / g++ will 15

Catching Sub2 class objects struct Base virtual void temp() ; struct Sub1 : public Base void temp() ; struct Sub2 : public Base void temp() ; Sub-class Sub2 object is thrown Which catch clause will be used? int test1() try Sub2* ps2 = new Sub2; throw ps2; A B C D catch ( Sub1& b ) cout << "Sub1" << endl; catch ( Base& b ) cout << Base" << endl; catch ( Sub2& b ) cout << "Sub2" << endl; catch (... ) cout << "Other" << endl; 16

Answer D Check catches in order: It is not a Sub1 It is not a Base It is not a Sub2 catches all exceptions Pointers are not objects Objects are not pointers Note: References and objects will match & Just says whether a copy is made or not 17

Aside: exceptions and throw() throw() at the end of the function declaration limits the exceptions which can be thrown It is optional In Java, throws <types> is mandatory If specified, then all exception types which can be thrown by function must be specified Throwing a different type will terminate the program Examples: void MyFunction(int i) throw(); Function will not throw exceptions void MyFunction(int i) throw(int); Function will only throw ints as exceptions void MyFunction(int i) throw(...); Function could throw ANY exception 18

Why does C++ not need finally? 19

What is wrong with this function? void foo() int* iarray = new int[100]; for (int i=0;i<100;i++) iarray[i] = rand(); if ( (iarray[i]%5) == 0 ) cout << "end " << i; return; Allocate memory Set each element to a random value End function if random number gives specific values cout << iarray[i] << " "; delete [] iarray; Free memory Note: This example has nothing directly to do with exceptions/exception handling, yet 20

Prematurely ending functions #include <iostream> using namespace std; struct MyClass MyClass() cout << "C"; ~MyClass() cout << "D"; ; void bar() throw 1; Throwing an uncaught exception will terminate the function, as if return was used. Objects on the stack will be destroyed correctly. void foo() MyClass* pob = new MyClass; bar(); delete pob; bar() throwing an int main() exception will mean delete is not called try for pob foo(); catch(... ) cout << "E"; cout << endl; 21

The problem // Function which may throw an exception void bar() throw 1; Note: no throws / throw on the function If you add a throw() on a function then you are guaranteeing that it ONLY throws those exceptions (throw any others and program ends) // This function throws an exception so the // objects are not destroyed void foo() // Create objects MyClass* pob1 = new MyClass; // Call function which may throw an exception bar(); delete pob1; Function ends before here The delete never gets called Objects not deleted Memory not freed 22

Code to open and use a file void version1() FILE* f = fopen( "out1.txt", "w" ); fprintf( f, "Output text" ); // Do something which throws exception or returns? throw 1; // Never gets to the close, so file possibly // not flushed until process ends printf("closing file manually\n" ); fclose(f); In Java we may put a finally clause in for the close, to ensure that the code to close the file is called, regardless of how the function exits. This is more tricky in C++ than Java because we don t know what will throw an exception 23

RAII : Resource Acquisition Is Initialisation A useful concept to understand 24

When a function ends Remember back to the discussion of the stack When a function ends, its stack frame is removed ALL stack objects (local variables) are destroyed Destructors are called for each This applies even if the function is ended due to an exception! RAII takes advantage of this My opinion (only): may be better named in this case: Resource Release On Object Destruction (RROOD?) On initialisation, get the resource On destruction, release the resource Example/summary: Create stack object to wrap the thing you need to release When stack object is destroyed, the thing gets released (e.g. file closed) Note: Java has no stack objects and no proper destructors only has: protected void finalize() : Before reclaiming the memory occupied by an object that has a finalizer, the garbage collector will invoke that object's finalizer. 25

Simplest(?) file wrapper class class Wrapper public: FILE* pfile; // No constructor - default created // Key part is the destructor! ~Wrapper() fclose(pfile); ; void version2a() Wrapper w; w.pfile = fopen( "out2a.txt", "w" ); fprintf( w.pfile, "Output text" ); // Do something which // e.g. throw exception throw 1; // Never gets to close // but we don't care //fclose(w.pfile); 26

A better wrapper class class MyFile FILE* pfile; public: // Constructor MyFile( const char* szfilename, const char* sztype = "r" ) : pfile(null) pfile = fopen( szfilename, sztype ); // Conversion operator operator FILE*() return pfile; ; // Is file open? bool isopen() return pfile!= NULL; // Close file if open void close() if ( pfile!= NULL ) fclose( pfile ); pfile = NULL; // Destructor!!! ~MyFile() close(); 27

Using the wrapper void version2b() // FILE* f=fopen("out2.txt","w"); MyFile file( "out2.txt", "w" ); fprintf( file, "Output text" ); class MyFile public: MyFile(... ) fopen( ); // Do something which throws // exception or returns? throw 1; // Never gets to the close below // but we don't care file.close(); operator FILE*() return pfile; void close() ~MyFile() close(); ; 28

Wrapping pointers 29

Wrapping pointers : int* class Deleter public: int* pob; // wrapped ptr // construct from pointer Deleter(int *pob = NULL) : pob(pob) // destroy the object ~Deleter() if ( pob ) delete pob; ; class ArrayDeleter public: int* parray; // construct from pointer ArrayDeleter( int* parray = NULL) : parray(parray) // destroy the array ~ArrayDeleter() if ( parray ) delete [] parray; ; 30

Wrapping pointers : templates template<class T> class Deleter public: T* pob; // wrapped pointer // construct from pointer Deleter(T *pob = NULL) : pob(pob) // destroy the object ~Deleter() if ( pob ) delete pob; ; template<class T> class ArrayDeleter public: T* parray; // construct from pointer ArrayDeleter( T* parray = NULL) : parray(parray) // destroy the array ~ArrayDeleter() if ( parray ) delete [] parray; ; 31

Summary 32

Other Exception Comments The destructor is guaranteed to be called for a stack object when the stack frame is destroyed It is the only function which we can guarantee will be called when an exception occurs 1. Throwing an exception while there is an uncaught exception will end the program Ensure that exceptions cannot be thrown from within a destructor because the destructor could be called as a result of an exception, e.g. to destroy objects on the stack 2. Not catching a thrown exception will end the program 33

The problem of pointers Throwing an exception is similar to a return Except that you get the value in a different way And it will keep returning from functions until caught When exceptions are thrown: Objects on the stack are destroyed (destructor called) Memory allocated dynamically will not be freed You need to either create objects on the stack, or free them yourself in every return and whenever an exception is thrown e.g. catch exception, delete object, re-throw You could wrap the pointers in stack objects Destructor for stack object should then call delete/free() on the wrapped pointer to delete the object/free() the memory The auto_ptr template class is designed for this purpose see standard class library 34

Exceptions Advice Try to catch (and handle) an exception as close as possible to the place it was generated Do not catch an exception if you cannot do something with it (leave it to your caller) If you throw exceptions, prefer to throw standard class library exceptions, or sub-classes of these Choose a meaningful exception My suggestion and ONLY a suggestion: There is a risk involved in using exceptions i.e. less control over the flow of control, like an implicit return, so, use exceptions only for exceptional circumstances 35

Next Lecture Operator overloading Strings and streams Short comments/examples about file access 36