© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.

Slides:



Advertisements
Similar presentations
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
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.
CS102--Object Oriented Programming
1 Chapter 17-2 Templates and Exceptions Dale/Weems.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
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.
 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.
1 Lecture 8 OOP Course. 9. Exceptions Error handling in C++ Error handling in C++
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
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.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
CS Advanced C++ Exception Handling Topic #5.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
Object Oriented Programming
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 13 - Exception Handling Outline 13.1Introduction 13.2When Exception Handling Should Be Used.
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?? }
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.
Java Programming: Guided Learning with Early Objects
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
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.
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 in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
Exception Handling Outline 23.1 Introduction
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
LECTURE LECTURE 14 Exception Handling Textbook p
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
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.
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.
IS 0020 Program Design and Software Tools
Exceptions Error Handling and Recovery
Why exception handling in C++?
EXCEPTION HANDLING.
Chapter 14: Exception Handling
Exception Handling.
Exceptions 1 CMSC 202.
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
Java Programming: From Problem Analysis to Program Design, 4e
CMSC 202 Lesson 20 Exceptions 1.
Presentation transcript:

© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0

© Copyright Eliyahu Brutman Chapter 12 – Exceptions Version 1.0

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 3 Introduction to Exception Handling Definition: An exception is any unusual event, either erroneous or not, detectable by either hardware or software, that may require special processing Without exception handling When an exception occurs, control goes to the operating system, where typically  an error message is displayed  the program is terminated With exception handling Programs are allowed to trap exceptions There is a possibility to fix the problem and continuing execution

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 4 Possible Naïve Solutions Exit the Program Isn ’ t it too strong OS already does the same Return Error Code Need to check the return code for every call Raise a Flag Need to check the flag after every operation Call a Special Code to Correct the Error But when shall we call it?

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 5 Motivation A mechanism which allows two components to survive runtime program anomaly Encountering such an anomaly (division by zero, access to an array outside its bound, etc.), may need an immediate handling The handling may reside in a different component, which we need to communicate The encountering components throws an exception The handling code, catches the exception, and handles it accordingly

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 6 Example Lets consider class stack const int MAX_ELEM=10; template class Stack { Tm_arr[size]; intm_index; public: Stack() : m_index(0) {} void Push(T elemP) { m_arr[m_index] = elemP; m_index++;} T& Pop() { m_index--; return m_arr[m_index]; } int Index() const { return m_index; } };

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 7 Exception Handling Syntax Exception Handlers try { -- code that is expected to raise an exception } catch (formal parameter) { -- handler code }...

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 8 Class Anomalies What happens if we pop() an empty stack? What happens if we push() on a full stack? We decide that these situations need to be handled in a special manner, since they are anomalies of the class behavior. First we define classes of exceptions which may be thrown Upon anomaly detection, we will throw an exception class popOnEmpty { /* … */ } class pushOnFull { /* … */ }

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 9 Example Our code would now change No need to examine the returned value for checking for success. … void Push(T elemP) { if (m_index>=size) throw pushOnFull(); // an object is throws m_arr[m_index] = elemP; m_index++;} T& Pop() { if (m_index<=0) throw popOnEmpty(); // an object is thrown m_index--; return m_arr[m_index]; } … };

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 10 Try…Catch Blocks Wrap the code which needs to be “ exception sensitive ”, and react to raised exceptions, in a try { … } catch { … } blocks The client ’ s code look now as following int main() { try{ Stack si; si.Pop(); si.Push(5); si.Pop(); } catch (popOnEmpty) { cout << "stack is empty !!" << endl; } };

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 11 Try…Catch Blocks When exception is thrown, execution resumes in the “ closest ” catch clause handling the exception. If no catch clause exists capable of handling the exception, program execution resumes at the terminate() function. Variables declared within the try block cannot be referred to at the catch clause, since they are local to the block. int main() { try{ Stack si; si.Pop(); si.Push(5); si.Pop(); } catch (popOnEmpty) { cout << "stack is empty !!" << endl; } cout << “Execution resumes here” << endl; }; Execution does Not resume here Type declaration

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 12 Exception-Handling Control Flow

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 13 Throwing Objects Why throw an object? Additional data encapsulated An object is created upon invoking the throw statement Can be created with additional data, passed to Ctor Object is destroyed after the catch clause ends

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 14 Stack Unwinding Up the chain of nested function calls, a suitable catch clause is searched for Upon functions and compound statements exit, stack is being unwound Lifetime of local variables ends Destructors are called If no handler is supplied, terminate() is called Since exception is a situation, where the program cannot continue execution in a normal manner By default terminate() calls abort() Similar to function call behavior But information to set up a function call is not available at compile time, run-time support is needed

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 15 Re-throwing and Catch All After some corrective action, a catch clause may throw an exception to be further handled, passing the exception to another catch clause, by throw. General exception handling can be specified catch( … ) { // place code here } If specified with combination, must be specified last, since evaluation is evaluated in turn.

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 16 Exception Specification Function interface need to be as precise as possible, it is the contract between several codes Client code may need to prepare for specific handling Best is to provide exception specification with the method declaration This will help the compiler to check consistency, to check that no other exceptions are thrown It follows the function parameter list

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 17 Exception Specification … void Push(T elemP) throw(pushOnFull) { if (m_index>=size) throw pushOnFull(); // an object is throws m_arr[m_index] = elemP; m_index++;} T& Pop() throw(popOnEmpty) { if (m_index<=0) throw popOnEmpty(); // an object is thrown m_index--; return m_arr[m_index]; } … };

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 18 Nesting try Blocks Exceptions are always handled by closest matching handler try { throw 5; } catch (int x) { cout << x << endl; // exception will be caught here } } catch (int x) { cout << x-5 << endl; }

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 19 Exceptions from Function Calls No different from nested try blocks Auto variables on stack are destroyed Exception jumps to nearest handler Allows exception handlers to be implemented far away from where the problem was May requires a knowledge of the issue packaged in exception object for appropriate handling

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 20 Exception Hierarchies Class types representing exceptions may be organized into groups or hierarchies Class Excp {} Class stackExcp : public Excp {} Class popOnEmpty : public stackExcp {} Class pushOnFull : public stackExcp {} Throwing an exception of type popOnEmpty may be caught by a handler expecting its base Therefore order should be handling more concrete types, and then handling more generic types Since handling is evaluated in order of specification, “ first match ” Ctors and Dtors are called in order like before

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 21 C++ Exception Hierarchy

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 22 Exceptions in Constructors Constructors cannot return errors Can throw exceptions Must use care! Destructors only called for fully constructed objects Subobjects (member variables that are objects) will get destroyed If memory allocated dynamically in constructor, it could get lost Exceptions are automatically rethrown from constructors

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 23 Exceptions Example A programmer-define ListException class #include using namespace std; class ListException: public exception { public: ListException (const string & message = “” ) : exception(message.c_str()) {} }; // end ListException

© Copyright Eliyahu Brutman Exceptions and Design Patterns // Fig. 13.1: fig13_01.cpp 2 // A simple exception-handling example that checks for 3 // divide-by-zero exceptions. 4 #include 5 #include 6 using namespace std; 7 8 // DivideByZeroException objects should be thrown by functions 9 // upon detecting division-by-zero exceptions 10 class DivideByZeroException : public exception { public: // constructor specifies default error message 25 DivideByZeroException::DivideByZeroException() 26 : exception( "attempted to divide by zero" ) {} }; // end class DivideByZeroException 29 Define new exception class (inherit from exception ). Pass a descriptive message to the constructor.

© Copyright Eliyahu Brutman Exceptions and Design Patterns // perform division and throw DivideByZeroException object if 27 // divide-by-zero exception occurs 28 double quotient( int numerator, int denominator ) 29 { 30 // throw DivideByZeroException if trying to divide by zero 31 if ( denominator == 0 ) 32 throw DivideByZeroException(); // terminate function // return division result 35 return static_cast ( numerator ) / denominator; 37 } // end function quotient int main() 40 { 41 int number1; // user-specified numerator 42 int number2; // user-specified denominator 43 double result; // result of division cout << "Enter two integers (end-of-file to end): "; 46 If the denominator is zero, throw a DivideByZeroException object.

© Copyright Eliyahu Brutman Exceptions and Design Patterns // enable user to enter two integers to divide 48 while ( cin >> number1 >> number2 ) { // try block contains code that might throw exception 51 // and code that should not execute if an exception occurs 52 try { 53 result = quotient( number1, number2 ); 54 cout << "The quotient is: " << result << endl; 56 } // end try 57 // exception handler handles a divide-by-zero exception 58 catch ( DivideByZeroException &divideByZeroException ) { 59 cout << "Exception occurred: " 60 << divideByZeroException.what() << endl; 61 } // end catch cout << "\nEnter two integers (end-of-file to end): "; 64 } // end while cout << endl; 67 return 0; // terminate normally 68 } // end main Notice the structure of the try and catch blocks. The catch block can catch DivideByZeroException objects, and print an error message. If no exception occurs, the catch block is skipped. Member function what returns the string describing the exception.

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 27 fig13_01.cpp output (1 of 1) Enter two integers (end-of-file to end): The quotient is: Enter two integers (end-of-file to end): Exception occurred: attempted to divide by zero Enter two integers (end-of-file to end): ^Z

© Copyright Eliyahu Brutman Exceptions and Design Patterns - 28 When TO Use Exceptions Fix the problem and try again Patch the problem and continue Make a complex error mechanism simpler Make code safer (catch fatal errors)