Title: Ch 11. Exception Handling
1Ch 11. Exception Handling
- Timothy Budd
- Oregon State University
2Introduction
- 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.
3Flags 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
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
5- errono should always be checked after calling any
function in which it might be set. - include lterrnogt // 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)
6The 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. -
7The Assertion Library
- include ltcassertgt // include assertion
package ...assert (size ! 0) // check size
before dividingdouble val sum / size // do
calculation - Never turn off assertion checking.
8The 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.
9- include ltcsetjmpgt // include setjmp library...
- jmp_buf Processing_Failed // create a jump
buffer - if (setjmp(Processing_Failed)) ... // handle
error case - else ... doProcessing() // handle program
execution
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 call doMoreProcessing(
)void doMoreProcessing() ... if
(somethingWrong) longjmp (Processing_Failed,
13)
11Activation Record Stack
Local data for function doMoreProcessing
anObject
Local data for function doProcessing
Local data for functin main
Local data for function main
12Signals
- 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 ltsignal.hgt // include signal
definitionsvoid handler (int a) // handle the
signal // ... // reset the signal
handler signal (a, handler)
13Exception Types
- Exception in C need not be a subclass of
Throwable. - The value thrown in conjunction with an exception
can be any type.
14- A class hierarchy in the header file stdexcept in
STL - exception logic_error length_error domai
n_error out_of_range invalid_argument runt
ime_error range_error overflow_error unde
rflow_error bad_alloc bad_cast bad_exception
bad_typeid
15- Catch-all exception handler in Java.
-
- // Java Catch-All Exampletry // ...
catch (Exception e) // catch all
exceptions // ...
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 actions throw
// pass action on to higher level
17Rethrowing 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.
18No 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.
19- class CleanUp CleanUp () // ... put
common clean up code here //...try
CleanUp dummy //...catch (IOError e)
// ...catch (RunTimeError e) //
...// ... continue with execution
20Reference 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.
21Exception 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.
22- 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")
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 specifiedint h () throw ()
// throws no exceptions - Backward compatibility for legacy code.
24- 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" -
25Standard 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
26- void f () throw (string)
- // ...g()
-
- void g ()
- // why not throw an irrational value?throw
3.14159