ch 11. exception handling timothy budd oregon state university
TRANSCRIPT
![Page 1: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/1.jpg)
Ch 11. Exception Handling
Timothy Budd
Oregon State University
![Page 2: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/2.jpg)
Ch 11. Exception Handling 2
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.
![Page 3: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/3.jpg)
Ch 11. Exception Handling 3
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
![Page 4: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/4.jpg)
Ch 11. Exception Handling 4
• 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
![Page 5: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/5.jpg)
Ch 11. Exception Handling 5
• 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);
}
![Page 6: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/6.jpg)
Ch 11. Exception Handling 6
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.
![Page 7: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/7.jpg)
Ch 11. Exception Handling 7
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.
![Page 8: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/8.jpg)
Ch 11. Exception Handling 8
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.
![Page 9: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/9.jpg)
Ch 11. Exception Handling 9
# 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
}
![Page 10: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/10.jpg)
Ch 11. Exception Handling 10
• 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 calldoMoreProcessing();
}
void doMoreProcessing() {...
if (somethingWrong)longjmp (Processing_Failed, 13);
}
![Page 11: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/11.jpg)
Ch 11. Exception Handling 11
Activation Record Stack
anObject
Local data forfunctin main
Local data for function doProcessing
Local data for function doMoreProcessing
Local data for function main
![Page 12: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/12.jpg)
Ch 11. Exception Handling 12
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 handlersignal (a, handler);
}
![Page 13: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/13.jpg)
Ch 11. Exception Handling 13
Exception Types
• Exception in C++ need not be a subclass of Throwable.
• The value thrown in conjunction with an exception can be any type.
![Page 14: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/14.jpg)
Ch 11. Exception Handling 14
• A class hierarchy in the header file stdexcept in STL
exceptionlogic_error
length_errordomain_errorout_of_rangeinvalid_argument
runtime_errorrange_erroroverflow_errorunderflow_error
bad_allocbad_castbad_exceptionbad_typeid
![Page 15: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/15.jpg)
Ch 11. Exception Handling 15
• Catch-all exception handler in Java.
// Java Catch-All Exampletry {
// ... } catch (Exception e) { // catch all exceptions
// ...}
![Page 16: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/16.jpg)
Ch 11. Exception Handling 16
• 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 actionsthrow; // pass action on to higher level
}
![Page 17: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/17.jpg)
Ch 11. Exception Handling 17
Rethrowing Exceptions• In Java, a catch clause can rethrow an exception.
try { // Java rethrow exception example// ...
}catch (exception e) {
// perform some actionthrow e; // resend exception
}
• C++ allows simply an unadorned throw statement, which is interpreted to throw the same value as the current catch clause.
![Page 18: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/18.jpg)
Ch 11. Exception Handling 18
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.
![Page 19: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/19.jpg)
Ch 11. Exception Handling 19
class CleanUp {~CleanUp ()
{// ... put common clean up code here}
};
//...
try {CleanUp dummy;//...
}catch (IOError & e) {
// ...}catch (RunTimeError & e) {
// ...}// ... continue with execution
![Page 20: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/20.jpg)
Ch 11. Exception Handling 20
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.
![Page 21: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/21.jpg)
Ch 11. Exception Handling 21
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.
![Page 22: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/22.jpg)
Ch 11. Exception Handling 22
class ParseException {public:
// constructorsParseException (string & why) : reason(why) { }ParseException (ParseException & why)
: reason(why.reason) { }
// operatorsvoid operator = (ParseException & why)
{ reason = why.reason; }operator string () { return reason; }
private:string reason;
}
...// throw an error, creates a temporary valuethrow ParseException("missing expression");
![Page 23: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/23.jpg)
Ch 11. Exception Handling 23
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.
![Page 24: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/24.jpg)
Ch 11. Exception Handling 24
• Always document a potential exception by placing a throw list in the function header.
class Parent { // do think the throw an exceptionpublic:
virtual void test (int i) { printf("parent test"); }};
class Child extends Parent {public:
virtual void test (int i) {
throw "executed child test";}
};
![Page 25: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/25.jpg)
Ch 11. Exception Handling 25
Standard Exceptions• Only a handful of exception can be
generated by function in the STL, including the following:
Name Thrown by
bad_alloc The operator new
bad_cast Dynamic cast operator
bad_typeid The typeid function
out_of_range Bitset subscript, vector functin at
invalid_argument Ditset constructor
![Page 26: Ch 11. Exception Handling Timothy Budd Oregon State University](https://reader030.vdocument.in/reader030/viewer/2022032517/56649cba5503460f94981a9c/html5/thumbnails/26.jpg)
Ch 11. Exception Handling 26
void f () throw (string)
{// ...g();
}
void g ()
{// why not throw an irrational value?throw 3.14159;
}