Rossella Lau Lecture 9, DCO10105, Semester B,2005-6 DCO10105 Object-Oriented Programming and Design  Lecture 9: Application with Exception Handling 

Slides:



Advertisements
Similar presentations
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
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.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
1 Handling Exceptions COSC 1567 C++ Programming Lecture 11.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 23 - Exception Handling Outline 23.1Introduction 23.2When Exception Handling Should Be Used 23.3Other.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
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.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Exception Handling: A Deeper.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
1 CSC241: Object Oriented Programming Lecture No 28.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exceptions COMPSCI 105 S Principles of Computer Science.
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.
Chapter 12: Exception Handling
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  Due to poor understanding of the problem and solution.
Java Programming: Guided Learning with Early Objects
Rossella Lau Lecture 1, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 1: Introduction What this course is about:
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.
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.
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.
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.
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
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
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.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
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.
C++ Exceptions.
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
Why exception handling in C++?
Part IX Fundamentals of C and C++ Programming Exception Handling
Chapter 14: Exception Handling
Exception Handling Chapter 9.
Chapter 17 Templates and Exceptions Part 2
Exception Handling Chapter 9 Edited by JJ.
Part B – Structured Exception Handling
Exceptions 1 CMSC 202.
Lecture 11 Objectives Learn what an exception is.
Department of Computer and Information Science, School of Science, IUPUI Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Rossella Lau Lecture 9, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 9: Application with Exception Handling  Popular usage of polymorphism in applications  Exception handling -- By Rossella Lau

Rossella Lau Lecture 9, DCO10105, Semester B,  Polymorphism – many types  Same classes can play as different types (of ancestors) Static binding with pointer  Same expressions can perform different operations Dynamic binding with pointer and virtual function Functions of sub-class can override the function with identical signature in the base class Samples in bindingPlayer3.cpp : donald->print() can invoke print() in Donald and print() in Dewey according to the actual object’s type Polymorphism

Rossella Lau Lecture 9, DCO10105, Semester B, Popular usage of polymorphism  Data in the same family class can be placed into a single container  E.g., vector publications;  To add a publication: publications.push_back(new Publication);  Book is a Publication: publications.push_back(new Book);  Then, a simple loop can print different details: for ( int i=0; i < publications.size(); i++) publications[i]->print();

Rossella Lau Lecture 9, DCO10105, Semester B, The sample application: Mini book shop

Rossella Lau Lecture 9, DCO10105, Semester B, Details of the Publication family

Rossella Lau Lecture 9, DCO10105, Semester B, The sample program set  The application: bookshop.cpp  Classes:  Publication.h  Book.h  Magazine.h  Catalog.h  OrderItem.h  Order.h  Sales.h  InputException.h

Rossella Lau Lecture 9, DCO10105, Semester B, Input check  Before a datum can be input, one should also guarantee the input device works properly  In C++, some user input can put the input device (istream) into a fail state and it cannot work properly; see slide 6-8 of Lecture 2  Then, a user input involves data domain check  A popular process: uses a loop to prompt user until a correct input is entered bool done = false; do { … // user prompt … // accept input … // device check // domain check if (……) // correct done = true; else … // error } while (!done)

Rossella Lau Lecture 9, DCO10105, Semester B, Exception handling  Error state or invalid input is an undesirable situation that makes program logic complicated, and sometimes disturbs the logic of normal operations  OOP uses exception handling to manage undesirable situations  System exceptions: logic_error & runtime_error Some popular derived sub-classes: invalid_argument, out_of_range, overflow_error, underflow_error  User defined exceptions: a user can use basic data types as exceptions or create its own exception classes

Rossella Lau Lecture 9, DCO10105, Semester B, Exceptions  Some system functions will throw exception(s) to allow the calling function to notify there is an exception (unexpected result) from the function  type funID(…) throw exception1, exception2, … {}  A user can also throw exceptions to have systematic exception handling: throw exception;  To manage the exception: use try -- catch

Rossella Lau Lecture 9, DCO10105, Semester B, A simple example try { cin >> input; if (!cin) throw InputException(); //domain check if (0 = input) done = true; else throw InputException("Invalid choice!"); } catch (InputException ie) { cerr << ie.what() << endl; const int DEFAULT_LINE_LENGTH = 100; cin.clear(); cin.ignore (DEFAULT_LINE_LENGTH, '\n'); }

Rossella Lau Lecture 9, DCO10105, Semester B, The sample user defined exception class InputException { private: string message; public: InputException(string str="Input Error!"): message(str) {} string what() {return message; } };  System exception classes usually provide a service function what() to return the error message

Rossella Lau Lecture 9, DCO10105, Semester B, Exceptions  Exception: undesirable event detectable during program execution  If exceptions occurred during execution  Programmer-supplied code terminated the program or  Program terminated with an appropriate error message  Can add exception-handling code at point where an error can occur (Malik’s slide: 16-4)  Example 16-1,2: Ch16_Ex1.cpp, Ch16_Ex2.cpp

Rossella Lau Lecture 9, DCO10105, Semester B, Handling Exceptions within a Program (continued)  Function assert:  Checks if an expression meets certain condition(s)  If conditions are not met, it terminates the program  Example: division by 0  If divisor is zero, assert terminates the program with an error message (Malik’s slide: 16-5)  Example 16-3: Ch16_Ex3.cpp

Rossella Lau Lecture 9, DCO10105, Semester B, C++ Mechanisms of Exception Handling  The try/catch block handles exceptions  Exception must be thrown in a try block and caught by a catch block  C++ provides support to handle exceptions via a hierarchy of classes (Malik’s slide: 16-6)

Rossella Lau Lecture 9, DCO10105, Semester B, try/catch Block  Statements that may generate an exception are placed in a try block  The try block also contains statements that should not be executed if an exception occurs  The try block is followed by one or more catch blocks (Malik’s slide: 16-7)

Rossella Lau Lecture 9, DCO10105, Semester B, try/catch Block (continued)  The catch block:  Specifies the type of exception it can catch  Contains an exception handler  If the heading of a catch block contains... (ellipses) in place of parameters  Catch block can catch exceptions of all types (Malik’s slide: 16-8)

Rossella Lau Lecture 9, DCO10105, Semester B,  General syntax of the try/catch block: (Malik’s slide: 16-9)

Rossella Lau Lecture 9, DCO10105, Semester B, try/catch Block (continued)  If no exception is thrown in a try block  All catch blocks for that try block are ignored  Execution resumes after the last catch block  If an exception is thrown in a try block  Remaining statements in that try block are ignored (Malik’s slide: 16-10)  Exercise: 16:2

Rossella Lau Lecture 9, DCO10105, Semester B, try/catch Block (continued)  The program searches catch blocks in order, looking for an appropriate exception handler  If the type of thrown exception matches the parameter type in one of the catch blocks:  Code of that catch block executes  Remaining catch blocks are ignored (Malik’s slide: 16-11)

Rossella Lau Lecture 9, DCO10105, Semester B, Throwing an Exception  For try/catch to work, the exception must be thrown in the try block  General syntax to throw an exception is: throw expression; where expression is a constant value, variable, or object (Malik’s slide: 16-12)  Example 16-5,6,7: Ch16_Exp5,6,7.cpp

Rossella Lau Lecture 9, DCO10105, Semester B, Throwing an Exception (continued)  The object being thrown can be  Specific object  Anonymous object  In C++  An exception is a value  throw is a reserved word (Malik’s slide: 16-13)

Rossella Lau Lecture 9, DCO10105, Semester B, Throwing an Exception: (Malik’s slide: 16-14)

Rossella Lau Lecture 9, DCO10105, Semester B, Order of catch Blocks  Catch block can catch  All exceptions of a specific type  All types of exceptions  A catch block with an ellipses (three dots) catches any type of exception  In a sequence of try/catch blocks, if the catch block with an ellipses is needed  It should be the last catch block of that sequence (Malik’s slide: 16-15)  Exercise: 16:3

Rossella Lau Lecture 9, DCO10105, Semester B, Using try/catch Blocks in a Program: (Malik’s slide: 16-16)

Rossella Lau Lecture 9, DCO10105, Semester B, Using C++ Exception Classes  C++ provides support to handle exceptions via hierarchy of classes  The function what returns the string containing exception object thrown by C++’s built-in exception classes  The class exception is:  The base class of the exception classes provided by C++  Contained in the header file exception (Malik’s slide: 16-17)

Rossella Lau Lecture 9, DCO10105, Semester B, Using C++ Exception Classes (continued)  Two classes derived from exception:  logic_error  runtime_error  logic_error and runtime_error are defined in header file stdexcept  The class invalid_argument deals with illegal arguments used in a function call (Malik’s slide: 16-18)

Rossella Lau Lecture 9, DCO10105, Semester B, Using C++ Exception Classes (continued)  The class out_of_range deals with the string subscript out_of_range error  The class length_error handles the error if  A length greater than the maximum allowed for a string object is used (Malik’s slide: 16-19)  Example 16-8,9: Ch16_Ex8.cpp, Ch16_Ex9.cpp

Rossella Lau Lecture 9, DCO10105, Semester B, Using C++ Exception Classes (continued)  If the operator new cannot allocate memory space  It throws a bad_alloc exception  The class runtime_error deals with errors that occur only during program execution  Classes overflow_error and underflow_error  Deal with arithmetic overflow and under-flow exceptions  Derived from the class runtime_error (Malik’s slide: 16-20)

Rossella Lau Lecture 9, DCO10105, Semester B, Creating Your Own Exception Classes  Programmers can create exception classes to handle exceptions not covered by C++’s exception classes and their own exceptions  C++ uses the same mechanism to process the exceptions you define as for built-in exceptions  You must throw your own exceptions using the throw statement  Any class can be an exception class (Malik’s slide: 16-21)  Example : Ch16_Ex10-13.cpp

Rossella Lau Lecture 9, DCO10105, Semester B, Rethrowing and Throwing an Exception  When an exception occurs in a try block  Control immediately passes to one of the catch blocks  A catch block either  Handles the exception or partially processes the exception and then rethrows the same exception OR  Rethrows another exception for the calling environment to handle (Malik’s slide: 16-22)

Rossella Lau Lecture 9, DCO10105, Semester B, Rethrowing and Throwing an Exception (continued)  The general syntax to rethrow an exception caught by a catch block is: throw; (in this case, the same exception is rethrown) or: throw expression; where expression is a constant value, variable, or object (Malik’s slide: 16-23)

Rossella Lau Lecture 9, DCO10105, Semester B, Rethrowing and Throwing an Exception (continued)  The object being thrown can be  A specific object  An anonymous object  A function specifies the exceptions it throws in its heading using the throw clause (Malik’s slide: 16-24)  Example 16-14,15: Ch16_Ex15.cpp, Ch16_Ex15.cpp

Rossella Lau Lecture 9, DCO10105, Semester B, Exception Handling Techniques  When an exception occurs, the programmer usually has three choices:  Terminate the program  Include code to recover from the exception  Log the error and continue (Malik’s slide: 16-25)

Rossella Lau Lecture 9, DCO10105, Semester B, Terminate the Program  In some cases, it is best to let the program terminate when an exception occurs  For example, if the input file does not exist when the program executes  There is no point in continuing with the program  The program can output an appropriate error message and terminate (Malik’s slide: 16-26)

Rossella Lau Lecture 9, DCO10105, Semester B, Fix the Error and Continue  In some cases, you will want to handle the exception and let the program continue  For example, if a user inputs a letter in place of a number  The input stream will enter the fail state  You can include the necessary code to keep prompting the user to input a number until the entry is valid (Malik’s slide: 16-27)  Example 16-16: Ch16_Ex16.cpp

Rossella Lau Lecture 9, DCO10105, Semester B, Log the Error and Continue (continued)  For example, if your program is designed to run a nuclear reactor or continuously monitor a satellite  It cannot be terminated if an exception occurs  When an exception occurs  The program should write the exception into a file and continue to run (Malik’s slide: 16-28)

Rossella Lau Lecture 9, DCO10105, Semester B, Summary  Polymorphism provides dynamic binding which reduces programming efforts for different data types within the same family  To manage an application better, exception handling should be employed

Rossella Lau Lecture 9, DCO10105, Semester B, Reference  Malik: 16  Sample program set (mini book shop):  bookShop.cpp, Publication.h, Book.h, Magazine.h, Catalog.h, OrderItem.h, Order.h, Sales.h, InputException.h -- END --