cs212: object oriented analysis and design lecture 20: exception handling-ii

22
CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Upload: dana-watts

Post on 14-Jan-2016

218 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

CS212: Object Oriented Analysis and Design

Lecture 20: Exception Handling-II

Page 2: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Recap of Lecture 19

• Exception handling

• Try, throw catch

• Stack unwinding

• Exception classes

Page 3: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Outline of Lecture 20

• Derived class exception

• Special scenarios

• Exception Specifications

• Rethrow

• Terminate() and unexpected()

Page 4: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Exception handling

• Terminate the program (an exception isn’t caught)

• Return a value representing ‘‘error,’’ (isn’t always feasible)

• Return a legal value and leave the program in an illegal state,

(calling function may not notice the error)

• Call a function supplied to be called in case of ‘‘error.’’

Exception they are insufficient, inelegant, and error prone.

Page 5: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Types of try block

• A try block to indicate which areas in your program that might throw exceptions you want to handle immediately

• A function try block to indicate that you want to detect exceptions in the entire body of a function

try { // statements }handlers {

// statemnts}

<Return type> functionName try <member initializer list> { // function body }handlers {

// statemnts} Demonstration

Page 6: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Exception Specifications

• We can restrict the type of exceptions that a function can throw outside of itself

• Prevent a function from throwing any exceptions whatsoever

• Add a throw clause to a function definition

• Data types contained in the comma-separated type-list may be thrown

ret-type func-name(arg-list) throw(type-list){

// ...}

Page 7: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Restricting Exceptions

• Throwing any other type of expression will cause abnormal program termination

• Standard library function unexpected()

• By default, this causes abort() to be called

• Specify your own unexpected handler if you like

• Demonstration

Page 8: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Rethrowing an Exception• A handler can’t completely handle the error.

• Rethrow an expression from within an exception handler

• Calling throw, by itself, with no exception

• This causes the current exception to be passed on to an outer try/catch sequence.

• Allow multiple handlers access to the exception

Page 9: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Re-Throw

void h (){

try {// code that might throw Math errors

}catch (Matherr) {

if (can_handle_it_completely) {// handle the Matherrreturn ;

}else {

// do what can be done here

throw ; // rethrow the exception}

}} Demonstration

Page 10: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Handling Derived-Class Exceptions

• Need to be careful in ordering the catch statements

• Trying to catch exception types involving base and derived classes

• Want to catch exceptions of both a base class type and a derived class type

• Demonstration

Page 11: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Resource Management

• A resource: is allocated, used and properly released

• ‘‘Proper release’’ is achieved by having the function that acquired it, release it before returning to its caller

void use_file (const char *fn ){

FILE * f = fopen (fn ,"w ");// use ffclose (f );

}

Page 12: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

“Resource acquisition is initialization”

• RAII: exception-safe resource management

• An object is not considered constructed until its constructor has completed

• Then and only then will stack unwinding call the destructor for the object.

• Don’t leave their objects in some ‘‘half-constructed’’ state

• Prevent “resource leak”

Page 13: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

RAII

• Encapsulate each resource into a class, where

• The constructor acquires the resource and establishes all class invariants or throws an exception if that cannot be done

• The destructor releases the resource and never throws exceptions

• Always use the resource via an instance of a RAII-class that either

• Has automatic storage duration

• Is a non-static member of a class whose instance has automatic storage duration

Page 14: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

terminate()

• During stack unwinding, a destructor throws an exception and that exception is not handled.

• The expression that is thrown also throws an exception, and that exception is not handled.

• The constructor or destructor of a nonlocal static object throws an exception, and the exception is not handled.

• A function registered with atexit() throws an exception, and the exception is not handled. The following demonstrates this:

Page 15: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

unexpected()

• A function with an exception specification throws an exception

• The exception is not listed in its exception specification

• The unexpected() function is called

• The unexpected() function calls the function pointed to by unexpected_handler

• By default, unexpected_handler points to the function terminate()

Page 16: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Setting the Terminate and Unexpected Handlers

• These functions call other functions to actually handle an error

• terminate() abort(); unexpected() terminate()

• Allows the program to take full control of the exception handling subsystem

• set_terminate(): terminate handler

• set_unexpected(): unexpected handler

• Demonstration

Page 17: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

uncaught_exception( )

• Detects if the current thread has a live exception object

• An exception has been thrown or rethrown and not yet entered a matching catch clause

• uncaught_exception detects if stack unwinding is currently in progress

• Detects how many exceptions have been thrown or rethrown

• And not yet entered their matching catch clauses

Page 18: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Standard Exception Classes (SEC)

• Exception classes derived from logic_error

• Exception classes derived from runtime_error

invalid_argument Invalid argument

out_of_range Argument value not in its expected range

length_error Length exceeds maximum capacity

domain_error Domain error reported by the implementation

range_error Range error in internal computation

underflow_error

Arithmetic underflow error

overflow_error Arithmetic overflow error

Page 19: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Exception and constructors

• How to report errors from a constructor

• Constructor does not return a separate value for a caller to test

• Return an object in a bad state

• Set a nonlocal variable (e.g., errno) to indicate that the creation failed

• Don’t do any initialization in the constructor

• Mark the object ‘‘uninitialized’’

Page 20: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Different scenarios

• Exceptions and New• What happens if X ´s constructor throws an exception?

• Resource Exhaustion• Resumption, Termination

• Exceptions and Member Initialization• A member initializer (directly or indirectly) throws an exception

• Exceptions in Destructors• Normal call• Call during exception handling

Page 21: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Exceptions That Are Not Errors

If an exception is expected and caught so that it has no bad effects on the behaviour of the program, then how can it be an error?

void f (Queue <X>& q ){try {

for (;;) {X m = q.get(); // throws ‘Empty’ if queue is empty/ / ...

}}catch (Queue <X >:: Empty) {

return ;}

}

Page 22: CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II

Thank youNext Lecture: Templates