Previous topic | Ada Home Page | Index

User defined exceptions

You can declare your own exception types

    TAN_ERROR : exception;

Example:

    procedure main is

        X, res    : FLOAT;
        TAN_ERROR : exception;


        function tan (X : FLOAT) return FLOAT is
        begin
            return sin(x)/cos(x);
        exception
            when NUMERIC_ERROR =>
                raise TAN_ERROR;
        end;


    begin

        PUT ("Enter a real number X : ");
        GET (X);
        res := tan(X);
        PUT ("Tan(X) is "); PUT(res); NEW_LINE;

    exception
        when TAN_ERROR =>
            PUT_LINE ("The tangent is too big");

    end;


Declaring exceptions in packages

NUMERIC_ERROR may arise in tan(x) function

Perhaps too unilateral to handle it locally, so prefer to pass an exception back to the caller.

What to pass back?

Where to declare TAN_ERROR?

An example shows how a package specification can define an exception; the package body can raise that exception when appropriate; and a user program can recognise and handle the exception.

Another example shows a package to do with vector arithmetic. Some vector operations only make sense if they are performed with vectors of the same length. The package can define an exception LENGTH_ERROR, to be raised if an operation is invoked with vectors of different lengths.


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