260 likes | 423 Views
Ch 11. Exception Handling. Timothy Budd Oregon State University. 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.
E N D
Ch 11. Exception Handling Timothy Budd Oregon State University
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. Ch 11. Exception Handling
Flags and Return Codes • When functions return an error flag, the result should always be checked. FILE * fp = fopen("myData", "r"); // open file for readif (fp == 0) ... // handle error caseelse ... // handle correctly opened case Ch 11. Exception Handling
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 fileif (! fin) { // convert to boolean and test // ... handle error case} FILE *fp = fopen("rahrah.dat", "w"); // open filefputc('O', fp); // write a few charactersfputc('S', fp);fputc('U', fp);if (ferror(fp)) // did an error occur in any of the previous? ... // handle error case Ch 11. Exception Handling
errono should always be checked after calling any function in which it might be set. # include <errno> // include errno definition ...double x = ...;errno = 0; // clear out error flagdouble 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);} Ch 11. Exception Handling
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. Ch 11. Exception Handling
The Assertion Library # include <cassert> // include assertion package ...assert (size != 0); // check size before dividingdouble val = sum / size; // do calculation • Never turn off assertion checking. Ch 11. Exception Handling
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. Ch 11. Exception Handling
# include <csetjmp> // include setjmp library... jmp_buf Processing_Failed; // create a jump buffer if (setjmp(Processing_Failed)) { ... // handle error case } else { ... doProcessing(); // handle program execution } Ch 11. Exception Handling
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);} Ch 11. Exception Handling
Activation Record Stack Local data for function doMoreProcessing anObject Local data for function doProcessing Local data for functin main Local data for function main Ch 11. Exception Handling
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 <signal.h> // include signal definitionsvoid handler (int a) { // handle the signal // ... // reset the signal handler signal (a, handler);} Ch 11. Exception Handling
Exception Types • Exception in C++ need not be a subclass of Throwable. • The value thrown in conjunction with an exception can be any type. Ch 11. Exception Handling
A class hierarchy in the header file stdexceptin 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 Ch 11. Exception Handling
Catch-all exception handler in Java. // Java Catch-All Exampletry { // ... } catch (Exception e) { // catch all exceptions // ...} Ch 11. Exception Handling
C++ permits ellipses to be used as the catch argument. // C++ Catch-All exampletry { // ...} catch ( ... ) { // catch all exceptions // ...} try { ...} catch ( ... ) { // catch all exceptions // perform clean up actions throw; // pass action on to higher level} Ch 11. Exception Handling
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. Ch 11. Exception Handling
No finally Clause • The finallyclause 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. Ch 11. Exception Handling
class CleanUp { ~CleanUp (){ // ... put common clean up code here }};//...try { CleanUp dummy; //...}catch (IOError & e) { // ...}catch (RunTimeError & e) { // ...}// ... continue with execution Ch 11. Exception Handling
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. Ch 11. Exception Handling
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. Ch 11. Exception Handling
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 valuethrow ParseException("missing expression"); Ch 11. Exception Handling
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 errorint 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. Ch 11. Exception Handling
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"; } }; Ch 11. Exception Handling
Standard Exceptions • Only a handful of exception can be generated by function in the STL, including the following: Ch 11. Exception Handling
void f () throw (string) {// ...g(); } void g () {// why not throw an irrational value?throw 3.14159; } Ch 11. Exception Handling