# Ada Programming/Exceptions


## Robustness

*Robustness* is the ability of a system or system component to behave
"reasonably" when it detects an anomaly, e.g.:

-   It receives invalid inputs.
-   Another system component (hardware or software) malfunctions.

Take as example a telephone exchange control program. What should the
control program do when a line fails? It is unacceptable simply to halt
--- all calls will then fail. Better would be to abandon the current
call (only), record that the line is out of service, and continue.
Better still would be to try to reuse the line --- the fault might be
transient. Robustness is desirable in all systems, but it is essential
in systems on which human safety or welfare depends, e.g., hospital
patient monitoring, aircraft fly-by-wire, nuclear power station control,
etc.

## Modules, preconditions and postconditions

A module may be specified in terms of its preconditions and
postconditions. A *precondition* is a condition that the module's inputs
are supposed to satisfy. A *postcondition* is a condition that the
module's outputs are required to satisfy, provided that the precondition
is satisfied. What should a module do if its precondition is not
satisfied?

-   Halt? Even with diagnostic information, this is generally
    unacceptable.
-   Use a global result code? The result code can be set to indicate an
    anomaly. Subsequently it may be tested by a module that can effect
    error recovery. Problem: this induces tight coupling among the
    modules concerned.
-   Each module has its own result code? This is a parameter (or
    function result) that may be set to indicate an anomaly, and is
    tested by calling modules. Problems: (1) setting and testing result
    codes tends to swamp the normal-case logic and (2) the result codes
    are normally ignored.
-   Exception handling --- Ada's solution. A module detecting an anomaly
    raises an exception. The same, or another, module may handle that
    exception.

The exception mechanism permits clean, modular handling of anomalous
situations:

-   A unit (e.g., block or subprogram body) may raise an exception, to
    signal that an anomaly has been detected. The computation that
    raised the exception is abandoned (and can never be resumed,
    although it can be restarted).
-   A unit may propagate an exception that has been raised by itself (or
    propagated out of another unit it has called).
-   A unit may alternatively handle such an exception, allowing
    programmer-defined recovery from an anomalous situation. Exception
    handlers are segregated from normal-case code.

## Predefined exceptions

The predefined exceptions are those defined in package
. Every language-defined run-time
error causes a predefined exception to be raised. Some examples are:

-   `Constraint_Error`, raised when a subtype's constraint is not
    satisfied
-   `Program_Error`, when a protected operation is called inside a
    protected object, e.g.
-   `Storage_Error`, raised by running out of storage
-   `Tasking_Error`, when a task cannot be activated because the
    operating system has not enough resources, e.g.

Ex.1

`  Name : String (1 .. 10);`\
`  ...`\
`  Name := "Hamlet"; `\
`                    `

Ex.2

`  `\
`     P := `` Int_Node'(0, P);`\
`  `` ``; `\
`            `

Ex.3 Compare the following approaches:

`  `` Compute_Sqrt (X    : ``  Float;`\
`                          Sqrt : `` Float;`\
`                          OK   : `` Boolean)`\
`  `\
`  `\
`     `` X >= 0 `\
`        OK := True;`\
`        `\
`        ...`\
`     `\
`        OK := False;`\
`     `` ``;`\
`  `` Compute_Sqrt;`\
`  `\
`  ...`\
`  `\
`  `` Triangle (A, B, C         : ``  Float;`\
`                      Area, Perimeter : `` Float;`\
`                      Exists          : `` Boolean)`\
`  `\
`     S  : `` Float := 0.5 * (A + B + C);`\
`     OK : Boolean;`\
`  `\
`     Compute_Sqrt (S * (S-A) * (S-B) * (S-C), Area, OK);`\
`     Perimeter := 2.0 * S;`\
`     Exists    := OK;`\
`  `` Triangle;`

A negative argument to Compute_Sqrt causes OK to be set to False.
Triangle uses it to determine its own status parameter value, and so on
up the calling tree, *ad nauseam*.

*versus*

`  `` Sqrt (X : Float) `` Float `\
`  `\
`     `` X < 0.0 `\
`        `` Constraint_Error;`\
`     `` ``;`\
`     `\
`     ...`\
`  `` Sqrt;`\
`  `\
`  ...`\
`  `\
`  `` Triangle (A, B, C         : ``  Float;`\
`                      Area, Perimeter : `` Float)`\
`  `\
`     S: `` Float := 0.5 * (A + B + C);`\
`  `\
`     Area      := Sqrt (S * (S-A) * (S-B) * (S-C));`\
`     Perimeter := 2.0 * S;`\
`  `` Triangle;`

A negative argument to Sqrt causes Constraint_Error to be explicitly
raised inside Sqrt, and propagated out. Triangle simply propagates the
exception (by not handling it).

Alternatively, we can catch the error by using the type system:

`  `` Pos_Float `` Float `` 0.0 .. Float'``;`\
`  `\
`  `` Sqrt (X : Pos_Float) `` Pos_Float `\
`  `\
`     `\
`     ...`\
`  `` Sqrt;`

A negative argument to Sqrt now raises Constraint_Error at the point of
call. Sqrt is never even entered.

## Input-output exceptions

Some examples of exceptions raised by subprograms of the **predefined
package**  are:

-   `End_Error`, raised by Get, Skip_Line, etc., if end-of-file already
    reached.
-   `Data_Error`, raised by Get in Integer_IO, etc., if the input is not
    a literal of the expected type.
-   `Mode_Error`, raised by trying to read from an output file, or write
    to an input file, etc.
-   `Layout_Error`, raised by specifying an invalid data format in a
    text I/O operation

Ex. 1

`  `\
`     A : Matrix (1 .. M, 1 .. N);`\
`  `\
`     `` I `` 1 .. M `\
`        `` J `` 1 .. N `\
`            `\
`               Get (A(I,J));`\
`            `\
`               `` Data_Error =>`\
`                  Put ("Ill-formed matrix element");`\
`                  A(I,J) := 0.0;`\
`            ``;`\
`         `` ``;`\
`     `` ``;`\
`  `\
`     `` End_Error =>`\
`        Put ("Matrix element(s) missing");`\
`  ``;`

## Exception declarations

Exceptions are declared similarly to objects.

Ex.1 declares two exceptions:

`  Line_Failed, Line_Closed: ``;`

However, exceptions are not objects. For example, recursive re-entry to
a scope where an exception is declared does *not* create a new exception
of the same name; instead the exception declared in the outer invocation
is reused.

Ex.2

`  `` Directory_Enquiries `\
\
`     `` Insert (New_Name   : `` Name;`\
`                       New_Number : `` Number);`\
\
`     `` Lookup (Given_Name  : ``  Name;`\
`                       Corr_Number : `` Number);`\
\
`     Name_Duplicated : ``;`\
`     Name_Absent     : ``;`\
`     Directory_Full  : ``;`\
\
`  `` Directory_Enquiries;`

## Exception handlers

When an exception occurs, the normal flow of execution is abandoned and
the exception is handed up the call sequence until a matching handler is
found. Any declarative region (except a package specification) can have
a handler. The handler names the exceptions it will handle. By moving up
the call sequence, exceptions can become anonymous; in this case, they
can only be handled with the  handler.

` F `` Some_Type `\
`  ... -- declarations (1)`\
\
`  ... -- statements (2)`\
` -- handlers start here (3)`\
`  `` Name_1 | Name_2 => ... -- The named exceptions are handled with these statements`\
`  `` `` => ...  -- any other exceptions (also anonymous ones) are handled here`\
` F;`

Exceptions raised in the declarative region itself (1) cannot be handled
by handlers of this region (3); they can only be handled in outer
scopes. Exceptions raised in the sequence of statements (2) can of
course be handled at (3).

The reason for this rule is so that the handler can assume that any
items declared in the declarative region (1) are well defined and may be
referenced. If the handler at (3) could handle exceptions raised at (1),
it would be unknown which items existed and which ones didn\'t.

## Raising exceptions

The **raise** statement explicitly raises a specified exception.

Ex. 1

`  `` `` Directory_Enquiries `\
`  `\
`     `` Insert (New_Name   : `` Name;`\
`                       New_Number : `` Number)`\
`     `\
`        …`\
`     `\
`        …`\
`        `` New_Name = Old_Entry.A_Name `\
`           `` Name_Duplicated;`\
`        `` ``;`\
`        …`\
`        New_Entry :=  `` Dir_Node'(New_Name, New_Number,…);`\
`        …`\
`     `\
`        `` Storage_Error => `` Directory_Full;`\
`     `` Insert;`\
`     `\
`     `` Lookup (Given_Name  : ``  Name;`\
`                       Corr_Number : `` Number)`\
`     `\
`        …`\
`     `\
`        …`\
`        `` `` Found `\
`           `` Name_Absent;`\
`        `` ``;`\
`        …`\
`     `` Lookup;`\
`  `\
`  `` Directory_Enquiries;`

## Exception handling and propagation

Exception handlers may be grouped at the end of a block, subprogram
body, etc. A handler is any sequence of statements that may end:

-   by completing;
-   by executing a **return** statement;
-   by raising a different exception (**raise** e;);
-   by re-raising the same exception (**raise**;).

Suppose that an exception *e* is raised in a sequence of statements *U*
(a block, subprogram body, etc.).

-   If *U* contains a handler for *e*: that handler is executed, then
    control leaves *U*.
-   If *U* contains no handler for *e*: *e* is *propagated* out of *U*;
    in effect, *e* is raised at the \"point of call" of *U*.

So the raising of an exception causes the sequence of statements
responsible to be abandoned at the point of occurrence of the exception.
It is not, and cannot be, resumed.

Ex. 1

`  ...`\
`  `\
`     `` Line_Failed =>`\
`        `` `\
`           Log_Error;`\
`           Retransmit (Current_Packet);`\
`        `\
`           `` Line_Failed =>`\
`              Notify_Engineer; `\
`              Abandon_Call;`\
`        ``;`\
`  ...`

## Information about an exception occurrence

Ada provides information about an exception in an object of type
Exception_Occurrence, defined in
 along with subprograms
taking this type as parameter:

-   Exception_Name: return the full exception name using the dot
    notation and in uppercase letters. For example, `Queue.Overflow`.
-   Exception_Message: return the exception message associated with the
    occurrence.
-   Exception_Information: return a string including the exception name
    and the associated exception message.

For getting an exception occurrence object the following syntax is used:

` ``;  `` ``;`\
`...`\
\
`  `` Error: High_Pressure | High_Temperature =>`\
`    Put ("Exception: ");`\
`    Put_Line (Exception_Name (Error));`\
`    Put (Exception_Message (Error));`\
`  `` Error: `` =>`\
`    Put ("Unexpected exception: ");`\
`    Put_Line (Exception_Information(Error));`\
`;`

The exception message content is implementation defined when it is not
set by the user who raises the exception. It usually contains a reason
for the exception and the raising location.

The user can specify a message using the procedure Raise_Exception.

\
`   Valve_Failure : ``;`\
\
`  ...`\
`  Raise_Exception (Valve_Failure'``, "Failure while opening");`\
`  ...`\
`  Raise_Exception (Valve_Failure'``, "Failure while closing");`\
`  ...`\
\
`  `` Fail: Valve_Failure =>`\
`    Put (Exception_Message (Fail));`\
`;`

Starting with Ada 2005, a simpler syntax can be used to associate a
string message with exception occurrence.

`-- `\
\
`   Valve_Failure : ``;`\
\
`  ...`\
`  `` Valve_Failure `` "Failure while opening";`\
`  ...`\
`  `` Valve_Failure `` "Failure while closing";`\
`  ...`\
\
`  `` Fail: Valve_Failure =>`\
`    Put (Exception_Message (Fail));`\
`;`

The  package also provides
subprograms for saving exception occurrences and re-raising them.

## See also

### Wikibook

-   Ada Programming

### Ada 95 Reference Manual

-   
-   
### Ada 2005 Reference Manual

-   
-   
### Ada Quality and Style Guide

-   **Chapter 4: Program Structure**
    -           -   
```{=html}
<!-- -->
```
-   **Chapter 5: Programming Practices**
    -           -   
        -   
        -   
        -   
```{=html}
<!-- -->
```
-   **Chapter 7: Portability**
    -           -   
        -   
Programming}}\|Exceptions

es:Programación en
Ada/Excepciones
