View
222
Download
2
Tags:
Embed Size (px)
Citation preview
Rossella Lau Lecture 9, DCO10105, Semester B,2005-6
DCO10105 Object-Oriented Programming and Design
Lecture 9: Application with Exception Handling
Popular usage of polymorphism in applicationsException handling
-- By Rossella Lau
Rossella Lau Lecture 9, DCO10105, Semester B,2005-6
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,2005-6
Popular usage of polymorphism
Data in the same family class can be placed into a single container
E.g., vector<Publication*> 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,2005-6
The sample application: Mini book shop
Rossella Lau Lecture 9, DCO10105, Semester B,2005-6
Details of the Publication family
Rossella Lau Lecture 9, DCO10105, Semester B,2005-6
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,2005-6
Input checkBefore 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,2005-6
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,2005-6
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,2005-6
A simple example
try { cin >> input; if (!cin) throw InputException(); //domain check if (0 <= input && 7 >= 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,2005-6
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,2005-6
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,2005-6
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,2005-6
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,2005-6
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,2005-6
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,2005-6
General syntax of the try/catch block:(Malik’s slide: 16-9)
Rossella Lau Lecture 9, DCO10105, Semester B,2005-6
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,2005-6
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,2005-6
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,2005-6
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,2005-6
Throwing an Exception:
(Malik’s slide: 16-14)
Rossella Lau Lecture 9, DCO10105, Semester B,2005-6
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,2005-6
Using try/catch Blocks in a Program: (Malik’s slide: 16-16)
Rossella Lau Lecture 9, DCO10105, Semester B,2005-6
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,2005-6
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,2005-6
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,2005-6
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,2005-6
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 16-10-13: Ch16_Ex10-13.cpp
Rossella Lau Lecture 9, DCO10105, Semester B,2005-6
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,2005-6
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,2005-6
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,2005-6
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,2005-6
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,2005-6
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,2005-6
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,2005-6
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,2005-6
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 --