Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II."— Presentation transcript:

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

2 Recap of Lecture 19 Exception handling Try, throw catch Stack unwinding Exception classes

3 Outline of Lecture 20 Derived class exception Special scenarios Exception Specifications Rethrow Terminate() and unexpected()

4 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.

5 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 } functionName try { // function body } handlers { // statemnts } Demonstration

6 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) { //... }

7 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

8 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

9 Re-Throw void h () { try { // code that might throw Math errors } catch (Matherr) { if (can_handle_it_completely) { // handle the Matherr return ; } else { // do what can be done here throw ; // rethrow the exception } Demonstration

10 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

11 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 f fclose (f ); }

12 “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”

13 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

14 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:

15 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()

16 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

17 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

18 Standard Exception Classes (SEC) Exception classes derived from logic_error Exception classes derived from runtime_error invalid_argumentInvalid argument out_of_rangeArgument value not in its expected range length_errorLength exceeds maximum capacity domain_errorDomain error reported by the implementation range_errorRange error in internal computation underflow_errorArithmetic underflow error overflow_errorArithmetic overflow error

19 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’’

20 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

21 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 & q ){ try { for (;;) { X m = q.get(); // throws ‘Empty’ if queue is empty / /... } catch (Queue :: Empty) { return ; }

22 Thank you Next Lecture: Templates


Download ppt "CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II."

Similar presentations


Ads by Google