Previous topic | Next topic | Ada Home Page | Index

Strategies for handling exceptions

Three levels of ambition:

  1. take control -- try to act so program can continue
  2. identify exception for handling elsewhere -- detect, identify, pass it on
  3. ignore -- program halts ("crashes")

Aim to control an exception in the part of the program where its effect can most sensibly be handled.


1. Take control

Example: tan(x) may be impossible to compute or represent

NUMERIC_ERROR exception can be detected and handled

Handle the exception locally; caller never realises anything was wrong.

    function TAN (X : FLOAT) return FLOAT is

    begin

        return SIN(X) / COS(X);

    exception

        when NUMERIC_ERROR =>

            if (SIN(X)>=0.0 and COS(X)>= 0.0) or
               (SIN(X)< 0.0 and COS(X)<  0.0) 
            then
                return  FLOAT'LAST;
            else
                return -FLOAT'LAST;
            end if;

    end TAN;


2. Pass exception back

raise statement in exception handler:

    function TAN (X : FLOAT) return FLOAT is

    begin

        return SIN(X) / COS(X);

    exception

        when NUMERIC_ERROR =>

            PUT_LINE ("The value of tangent is too big");
            raise;

    end TAN;


3. Ignore the exception

No example is needed of the third level of ambition. We are all familiar with that one! It is what we have been doing all the time up to now.


Previous topic | Next topic | Ada Home Page | Index
c-lokan@adfa.oz.au / 26 Feb 96