Presentation is loading. Please wait.

Presentation is loading. Please wait.

Ch 11. Exception Handling Timothy Budd Oregon State University.

Similar presentations


Presentation on theme: "Ch 11. Exception Handling Timothy Budd Oregon State University."— Presentation transcript:

1

2 Ch 11. Exception Handling Timothy Budd Oregon State University

3 Ch 11. Exception Handling2 Introduction Exception handling is a relatively new addition to the C++ and still not widely used. Prior to the introduction of the feature, programmers dealt with unusual situations in a number of different ways. Need to know alternative techniques that have been used to address similar problems.

4 Ch 11. Exception Handling3 Flags and Return Codes When functions return an error flag, the result should always be checked. FILE * fp = fopen("myData", "r"); // open file for read if (fp == 0)... // handle error case else... // handle correctly opened case

5 Ch 11. Exception Handling4 The stream I/O system does not return an error status flag directly, but rather it yields a value that can be converted into a boolean value that indicates the error: istream fin("filename.dat"); // open file if (! fin) { // convert to boolean and test //... handle error case } FILE *fp = fopen("rahrah.dat", "w"); // open file fputc('O', fp); // write a few characters fputc('S', fp); fputc('U', fp); if (ferror(fp)) // did an error occur in any of the previous?... // handle error case

6 Ch 11. Exception Handling5 errono should always be checked after calling any function in which it might be set. # include // include errno definition... double x =...; errno = 0; // clear out error flag double d = sqrt(x); if (errno == EDOM) // test global status flag... // handle error case // is sqrt evaluated first, or g? double d = sqrt(x) * g(); // worse, what happens if g clears // a flag that was set by sqrt ? double g () { errno = 0; return 3.14159 * sin(42); }

7 Ch 11. Exception Handling6 The Assertion Library Assertion package: run-time diagnostic information A boolean expression that should never be false if the program is operating correctly. If the value evaluate to false, a diagnostic error message is printed and the program is halted by calling the STL function abort.

8 Ch 11. Exception Handling7 The Assertion Library # include // include assertion package... assert (size != 0); // check size before dividing double val = sum / size; // do calculation Never turn off assertion checking.

9 Ch 11. Exception Handling8 The setjmp and longjmp Facility Prior to the introduction of exception in C++ setjmp: errors often occur many levels deep, rather than unwinding the sequence of calls, better to simply jump back to an earlier point in execution to handle the error. Avoid the setjmp facility in new code, as exceptions provide the same functionality.

10 Ch 11. Exception Handling9 # include // include setjmp library... jmp_buf Processing_Failed; // create a jump buffer if (setjmp(Processing_Failed)) {... // handle error case } else {... doProcessing(); // handle program execution }

11 Ch 11. Exception Handling10 When encounter an unrecoverable error, programmer can invoke the longjmp, passing as an argument the jump buffer and a nonzero integer value, rather than tracking back through the sequence of function invocations : void doProcessing() { ObjectType anObject; // declare an object value.. // go through several layers of function call doMoreProcessing(); } void doMoreProcessing() {... if (somethingWrong) longjmp (Processing_Failed, 13); }

12 Ch 11. Exception Handling11 Activation Record Stack anObject Local data for functin main Local data for function doProcessing Local data for function doMoreProcessing Local data for function main

13 Ch 11. Exception Handling12 Signals User hitting a break key, a floating point exception, a loss of carrier on a phone line, segmentation violation, or a bus error are reported to the program by means of a signal. A signal handler is a procedure that takes as an argument a single integer value. This integer is used to encode the type of signal being processed: # include // include signal definitions void handler (int a) { // handle the signal //... // reset the signal handler signal (a, handler); }

14 Ch 11. Exception Handling13 Exception Types Exception in C++ need not be a subclass of Throwable. The value thrown in conjunction with an exception can be any type.

15 Ch 11. Exception Handling14 A class hierarchy in the header file stdexcept in STL exception logic_error length_error domain_error out_of_range invalid_argument runtime_error range_error overflow_error underflow_error bad_alloc bad_cast bad_exception bad_typeid

16 Ch 11. Exception Handling15 Catch-all exception handler in Java. // Java Catch-All Example try { //... } catch (Exception e) { // catch all exceptions //... }

17 Ch 11. Exception Handling16 C++ permits ellipses to be used as the catch argument. // C++ Catch-All example try { //... } catch (... ) { // catch all exceptions //... } try {... } catch (... ) { // catch all exceptions // perform clean up actions throw; // pass action on to higher level }

18 Ch 11. Exception Handling17 Rethrowing Exceptions In Java, a catch clause can rethrow an exception. try { // Java rethrow exception example //... } catch (exception e) { // perform some action throw e; // resend exception } C++ allows simply an unadorned throw statement, which is interpreted to throw the same value as the current catch clause.

19 Ch 11. Exception Handling18 No finally Clause The finally clause in Java permits a section of code to be executed regardless of whether an exception is thrown. No similar facility in C++ Alternative way: create a dummy class and variable whose sole purpose is to launch a destructor when the try block is executed. Clean-up code is performed before the catch clauses.

20 Ch 11. Exception Handling19 class CleanUp { ~CleanUp () { //... put common clean up code here } }; //... try { CleanUp dummy; //... } catch (IOError & e) { //... } catch (RunTimeError & e) { //... } //... continue with execution

21 Ch 11. Exception Handling20 Reference as Exceptions The binding of a thrown value to an exception handler is a form of assignment. To avoid the slicing problem, exception handlers should declare their variables by reference.

22 Ch 11. Exception Handling21 Exception Class Clonability In Java, the value thrown is generally a newly created heap-based object, formed using the new operator. In C++, the object is often a nameless temporary value, formed by simply naming the class and any arguments used by the constructor. Always write a copy constructor for any user-defined exception class.

23 Ch 11. Exception Handling22 class ParseException { public: // constructors ParseException (string & why) : reason(why) { } ParseException (ParseException & why) : reason(why.reason) { } // operators void operator = (ParseException & why) { reason = why.reason; } operator string () { return reason; } private: string reason; }... // throw an error, creates a temporary value throw ParseException("missing expression");

24 Ch 11. Exception Handling23 No Need to Document Exception In C++, a function need not declare the possibility of throwing an exception in the function header. int f () throw (range_error); // will only throw range error int g (); // can possibly throw anything To indicate a function throws no exceptions, an empty list must be specified: int h () throw (); // throws no exceptions Backward compatibility for legacy code.

25 Ch 11. Exception Handling24 Always document a potential exception by placing a throw list in the function header. class Parent { // do think the throw an exception public: virtual void test (int i) { printf("parent test"); } }; class Child extends Parent { public: virtual void test (int i) { throw "executed child test"; } };

26 Ch 11. Exception Handling25 Standard Exceptions Only a handful of exception can be generated by function in the STL, including the following: NameThrown by bad_allocThe operator new bad_castDynamic cast operator bad_typeidThe typeid function out_of_rangeBitset subscript, vector functin at invalid_argumentDitset constructor

27 Ch 11. Exception Handling26 void f () throw (string) { //... g(); } void g () { // why not throw an irrational value? throw 3.14159; }


Download ppt "Ch 11. Exception Handling Timothy Budd Oregon State University."

Similar presentations


Ads by Google