C for Java Programmers - PowerPoint PPT Presentation

1 / 31
About This Presentation
Title:

C for Java Programmers

Description:

... way: create a dummy class and variable whose sole purpose ... Exception Class Clonability ... class Parent { // do you think it will throw an exception? public: ... – PowerPoint PPT presentation

Number of Views:30
Avg rating:3.0/5.0
Slides: 32
Provided by: seungs
Category:

less

Transcript and Presenter's Notes

Title: C for Java Programmers


1
C for Java Programmers
  • Chapter 11
  • Exception Handing

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.

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

4
Sometimes flags are indirect
  • The stream I/O system produces 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

5
What good is an error flag if nobody is checking
for it
  • 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

6
Errno is set by many functions, but must be
checked
  • 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
  • double d sqrt(x) g() // which is eval
    first?
  • double g () // worse, what if you clear a flag
  • errno 0 // that might have been set
  • return 3.14159 sin(42)

7
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
The Assertion Library
  • include ltcassertgt // include assertion
    package ...assert (size ! 0) // check size
    before dividingdouble val sum / size // do
    calculation
  • Never turn off assertion checking.

9
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
Example of setjmp
  • 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

11
On error, call longjmp
  • 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
Activation Record Stack
Local data for function doMoreProcessing
anObject
Local data for function doProcessing
Local data for functin main
Local data for function main
13
Longjmp does not clean up after itself
  • A call to longjmp simply pops the activation
    record stack
  • Does not call destructors properly for values
    being deleted
  • For this reason, should be avoided in new code

14
Signals
  • User hitting a break key, a floating point
    exception, a loss of carrier on a phone line,
    segmentation violation, or a bus error (or many
    more) are reported to the program by means of a
    signal.

15
Signal Handlers
  • 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)

16
Exception Types
  • Exception in C need not be a subclass of
    Throwable.
  • The value thrown in conjunction with an exception
    can be any type.

17
  • 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

18
Catching any exception
  • Catch-all exception handler in Java.
  • // Java Catch-All Exampletry // ...
    catch (Exception e) // catch all
    exceptions // ...

19
C does same thing with
  • // C Catch-All exampletry // ... catch (
    ... ) // catch all exceptions // ...
  • try ... catch ( ... ) // catch all
    exceptions // perform clean up actions throw
    // pass action on to higher level

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

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

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

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

24
  • 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")

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

26
Good form to document exceptions
  • class Parent // do you think it will 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"

27
Standard Exceptions
  • Only a handful of exception can be generated by
    function in the STL, including the following

28
Lax rules for checking exceptions
  • void f () throw (string) // you might think only
    strings are thrown
  • // ...g() // surprize!!
  • void g ()
  • // why not throw an irrational value?throw
    3.14159

29
Test your Understanding
  • What are some of the hazards of using flags to
    indicate exceptional conditions?
  • What is the name of the global flag set by many
    numeric and I/O operations?

30
Test your Understanding
  • Why should the use of longjmp be discouraged in
    new programs?
  • What type of value can be thrown in an exception?
    How is this different from Java?

31
Test your Understanding
  • How is the documentation that a function can
    throw an exception different in Java and C?
Write a Comment
User Comments (0)
About PowerShow.com