Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Week 11 Exceptions.

Slides:



Advertisements
Similar presentations
Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Week 6 Lab 2 is marked Hand in Lab 3 Questions from Last Week Operator Overloading.
Advertisements

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.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
COMP 121 Week 5: Exceptions and 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.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
. 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.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
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.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
 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?? }
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.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
Monday, Jan 13, 2003Kate Gregory with material from Deitel and Deitel Week 2 Questions from Last Week Control Structures Functions Lab 1.
February 11, 2005 More Pointers Dynamic Memory Allocation.
Exceptions Handling Exceptionally Sticky Problems.
Monday, Mar 31, 2003Kate Gregory with material from Deitel and Deitel Week 12 Labs 4 and 5 are back File IO Looking ahead to the final.
Monday, Feb 3, 2003Kate Gregory with material from Deitel and Deitel Week 5 Lab 1 comments Hand in Lab 2 Questions from Last Week Classes continued Lab.
HANDLING EXCEPTIONS Chapter 9. Outline  Learn about the limitations of traditional error-handling methods  Throw exceptions  Use try blocks  Catch.
CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
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.
© 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
LECTURE LECTURE 14 Exception Handling Textbook p
Exceptions Lecture 11 COMP 401, Fall /25/2014.
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.
Eighth Lecture Exception Handling in Java
Exceptions handling Try, catch blocks Throwing exceptions.
C ++ MULTIPLE CHOICE QUESTION
Exception handling.
C++ Exceptions.
IS 0020 Program Design and Software Tools
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.
Exceptions.
CMSC202 Computer Science II for Majors Lecture 16 – Exceptions
Jim Fawcett CSE687 – Object Oriented Design Spring 2001
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Handling Exceptionally Sticky Problems
Why exception handling in C++?
Exceptions with Functions
Chapter 17 Templates and Exceptions Part 2
Exceptions 1 CMSC 202.
Exceptions handling Try, catch blocks Throwing exceptions.
Handling Exceptionally Sticky Problems
Exceptions 10-May-19.
CMSC 202 Exceptions.
Exception Handling.
CMSC 202 Lesson 20 Exceptions 1.
Presentation transcript:

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Week 11 Exceptions

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Errors happen Predictable: –Users type bad data –End of file is reached –File opened is not in the right format Unpredictable –No more memory –File user browsed to is gone now –Hard drive is full

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Local Error Handling cout << “Enter a positive number “; cin >> x; while (x < 0) { cout << “Positive please “; cin >> x; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Delegate to an object cout << “Enter a positive number “; cin >> x; while (!obj.setx(x)) { cout << “Positive please “; cin >> x; } setx() returns false if it didn’t like the number Problem: how do you know what error message to provide?

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Delegate to an object cout << “Enter a positive number “; cin >> x; while (!obj.setx(x)) { cout << obj.errormessage(); cin >> x; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Not all errors can be handled locally Deep inside business logic you should not be contacting the user directly –This may be a GUI app and console output will be ignored –This may be running unattended –Better to report the error to calling code that knows how to reach the user

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel How to report errors? Classic approach is to return a signal value: false is good, but an error code may carry more information. –What if you need your return value for an answer? –What if the function doesn’t have a return value (eg constructor, override of a void function) –What if the code that called the function ignores the return value?

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel How to report errors? Set a global variable (traditional name is errno) –Still requires calling code to look at it –Multiple errors can tromp on each other You need a way to force the calling code to notice that something has gone wrong You want to pass information along with that notification

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Exceptions A non-ignorable notification (with supplementary information) that is thrown by code in trouble It can be caught by any code up the calling chain Catching code tries to recover, but cannot return execution to the trouble spot If your code doesn’t catch it, the operating system will (and it won’t be very pretty.)

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Signalling trouble Throw an exception if ( x < 3) throw "x is too small"; If you don’t write code to catch it, it’s an unhandled exception

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Unhandled Exceptions

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel What can you throw? A literal string such as “x is too small” A number (perhaps an error code) A struct An object –The most useful, since it can combine all these and even have methods that can be called from the catching code

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Throws list How do you know what to catch? –You can read the code –There’s an optional addition to the function prototype int foo (int x) throw(char*) Since it’s optional, it has very little effect –foo() can throw anything it likes –Code that calls foo() is not obligated to catch char* or any other kind of exceptions –It’s just for documentation

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel What happens when the exception is thrown? If the code is in a try block, the rest of the try block is skipped and control is transferred to the start of the appropriate catch block –Try and catch you will see shortly If the code is not in a try block, the rest of the function is skipped and control leaves the function –If the call to this function was in a try block, control goes to the catch associated with that try –If not, control leaves the function that called this function

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel An example void one(char* p) { cout << "entering one" << endl; two(p); cout << "back in one" << endl; } void two(char* p) { cout << "entering two" << endl; if (p) cout << p << endl; else throw "null pointer passed"; cout << "leaving two" << endl; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel When all goes well one("Hello"); Output: entering one entering two Hello leaving two back in one

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel When things go wrong one(NULL); Output: entering one entering two ---- exception is thrown --

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Catching the exception You need to set up a try block. This represents the group of statements you are going to try, that you know might throw an exception. Immediately following the try block, place a catch block. It will execute if an exception is thrown. If you catch and process the exception, execution can continue after the catch block and the program will not end abnormally.

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Catching the exception The try block does not have to be in the same function as the throw statement – in fact it usually is not. Remember that an exception is a way of signalling trouble back up to the code that called you

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Catching the exception void one(char* p) { cout << "entering one" << endl; try { two(p); } catch (char* troublestring) { cout << "two() has a problem: " << troublestring << endl; } cout << "back in one" << endl; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Output entering one entering two two() has a problem: null pointer passed back in one Notice that execution continued after the catch block.

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Catching the exception You can have several catch blocks to catch different types of exceptions (eg int and char*) catch (…) catches any kind of exception at all but you can’t print out what was thrown or otherwise work with it –You can stop your application from blowing up, but not much else

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Rethrowing Sometimes you catch an exception so that you can handle it and allow the application to recover Other times you catch an exception just so that you can do some local cleanup In those circumstances, your catch block can rethrow the exception: catch (Ex ex) { cout << "two() has a problem: " << ex << endl; throw; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Throwing an object class Ex { private: int errorcode; char* troublestring; public: Ex(int ec, char* ts): errorcode(ec), troublestring(ts) {} friend ostream& operator<<(ostream& o, const Ex& e); };

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Throwing an Object ostream& operator<<(ostream& o, const Ex& e) { o << "Exception: " << e.errorcode << " (“ << e.troublestring << ")" << endl; return o; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Throwing an Object void two(char* p) { cout << "entering two" << endl; if (p) cout << p << endl; else { Ex e(15, "null pointer passed"); throw e; } cout << "leaving two" << endl; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Catching an Object void one(char* p) { cout << "entering one" << endl; try { two(p); } catch (Ex ex) { cout << "two() has a problem: " << ex << endl; } cout << "back in one" << endl; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel STL Exception class The Standard Template Library defines a class called exception and a number of classes that inherit from it STL functions throw exceptions derived from exception and your code can too: –invalid_argument –out_of_range –overflow_error –etc

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Using STL Exceptions #include int stlthrower(int x) { if (x < 4) { invalid_argument e("x too small"); throw e; } return x; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Catching exceptions by reference try { stlthrower(10); stlthrower(0); } catch (exception& e) { cout << "caught: " << e.what() << endl; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Unwinding the stack When the exception is thrown, control leaves the function or try block Everything allocated on the stack goes out of scope, and the destructors are called Memory on the heap is not freed but pointers to it may be gone

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Unwinding the stack int foo (int x) { int i, j; Employee e; Employee* pe = new Employee(); if ( x < 3) throw "x is too small"; else cout << "x is " << x << endl; return x; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Unwinding the stack int foo (int x) { int i, j; Employee e; Employee* pe = new Employee(); if ( x < 3) throw "x is too small"; else cout << "x is " << x << endl; delete pe; return x; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Unwinding the stack int foo (int x) { int i, j; Employee e; Employee* pe = new Employee(); if ( x < 3) { delete pe; throw "x is too small"; } else cout << "x is " << x << endl; delete pe; return x; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Unwinding the Stack If you have code that deletes memory, ask yourself if it could be skipped when an exception is thrown. Consider moving the delete until after the catch block: void one(char* p) { cout << "entering one" << endl; Employee* pe = new Employee(); try { two(p); } catch (Ex ex) { cout << "two() has a problem: " << ex << endl; } cout << "back in one" << endl; delete pe; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Cleaning up Memory Putting the delete after the catch block won’t work if you rethrow the exception, because control is leaving the function on the rethrow You could put the delete in the catch block, before the rethrow, and also after it, for those times where there is no exception This is repetitive and error-prone

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Duplicate code catch (Ex ex) { cout << "two() has a problem: " << ex << endl; delete pe; throw; } cout << "back in one" << endl; delete pe;

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel STL Auto pointer When the stack unwinds, anything you allocated on the stack (int i; Employee e;) is taken care of for you no matter why you left Anything you allocated on the heap you have to take care of yourself What if you allocated something on the stack whose only job was to manage something on the heap?

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel STL Auto Pointer This memory manager object would have one variable: a pointer to something on the heap Constructor sets the variable Destructor calls delete using the pointer Operator -> and operator * give access to the object the pointer points to For type-safety, it should be a template

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel STL Auto Pointer template class auto_ptr { public: explicit auto_ptr(_Ty *_Ptr = 0) : _Myptr(_Ptr) {} ~auto_ptr() {delete _Myptr;} _Ty& operator*() const {return (*get());} _Ty *operator->() const {return (get());} _Ty *get() const {return (_Myptr);} private: _Ty *_Myptr; };

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Using an auto pointer void one(char* p) { cout << "entering one" << endl; auto_ptr pe(new Employee()); try { two(p); pe->display(); cout << *pe << endl; } catch (Ex ex) { cout << "two() has a problem: " << ex << endl; throw; } cout << "back in one" << endl; }

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel When to use Exceptions When the error is truly unexpected: out of memory, file has disappeared, etc When the code that can handle it is many function calls away from the code that will detect it When repeatedly checking function returns to pass back error codes will make code harder to read When there is a danger a programmer may forget to check a return code, or the return code is being used

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Exceptions hurt performance Compared to returning a value and checking it you will take a real performance hit by throwing an exception However modern compilers optimize so that trying, in the case where the exception isn’t thrown, actually runs more quickly than an if Reserve exceptions for exceptional circumstances –Never for user input errors!

Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel For Next class Bring your thoughts and questions, it’s our last lecture We’ll be covering File IO which is not hard at all