Ada Programming/Exceptions

< Ada Programming
Computing » Computer Science » Computer Programming » Ada Programming

Robustness

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

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?

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

Predefined exceptions

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

Ex.1

  Name : String (1 .. 10);
  ...
  Name := "Hamlet"; -- Raises Constraint_Error,
                    -- because the "Hamlet" has bounds (1 .. 6).

Ex.2

  loop
     P := new Int_Node'(0, P);
  end loop; -- Soon raises Storage_Error,
            -- because of the extreme memory leak.

Ex.3 Compare the following approaches:

  procedure Compute_Sqrt (X    : in  Float;
                          Sqrt : out Float;
                          OK   : out Boolean)
  is
  begin
     if X >= 0 then
        OK := True;
        -- compute √X
        ...
     else
        OK := False;
     end if;
  end Compute_Sqrt;
  
  ...
  
  procedure Triangle (A, B, C         : in  Float;
                      Area, Perimeter : out Float;
                      Exists          : out Boolean)
  is
     S  : constant Float := 0.5 * (A + B + C);
     OK : Boolean;
  begin
     Compute_Sqrt (S * (S-A) * (S-B) * (S-C), Area, OK);
     Perimeter := 2.0 * S;
     Exists    := OK;
  end 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

  function Sqrt (X : Float) return Float is
  begin
     if X < 0.0 then
        raise Constraint_Error;
     end if;
     -- compute √X
     ...
  end Sqrt;
  
  ...
  
  procedure Triangle (A, B, C         : in  Float;
                      Area, Perimeter : out Float)
  is
     S: constant Float := 0.5 * (A + B + C);
  begin
     Area      := Sqrt (S * (S-A) * (S-B) * (S-C));
     Perimeter := 2.0 * S;
  end 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:

  subtype Pos_Float is Float range 0.0 .. Float'Last;
  
  function Sqrt (X : Pos_Float) return Pos_Float is
  begin
     -- compute √X
     ...
  end 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 Ada.Text_IO are:

Ex. 1

  declare
     A : Matrix (1 .. M, 1 .. N);
  begin
     for I in 1 .. M loop
        for J in 1 .. N loop
            begin
               Get (A(I,J));
            exception
               when Data_Error =>
                  Put ("Ill-formed matrix element");
                  A(I,J) := 0.0;
            end;
         end loop;
     end loop;
  exception
     when End_Error =>
        Put ("Matrix element(s) missing");
  end;

Exception declarations

Exceptions are declared similarly to objects.

Ex.1 declares two exceptions:

  Line_Failed, Line_Closed: exception;

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

  package Directory_Enquiries is

     procedure Insert (New_Name   : in Name;
                       New_Number : in Number);

     procedure Lookup (Given_Name  : in  Name;
                       Corr_Number : out Number);

     Name_Duplicated : exception;
     Name_Absent     : exception;
     Directory_Full  : exception;

  end 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 be the others handler.

function F return Some_Type is
  ... -- declarations (1)
begin
  ... -- statements (2)
exception  -- handlers start here (3)
  when Name_1 | Name_2 => ... -- The named exceptions are handled with these statements
  when others => ...  -- any other exceptions (also anonymous ones) are handled here
end 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

  package body Directory_Enquiries is
  
     procedure Insert (New_Name   : in Name;
                       New_Number : in Number)
     isbeginif New_Name = Old_Entry.A_Name then
           raise Name_Duplicated;
        end if;
        …
        New_Entry :=  new Dir_Node'(New_Name, New_Number,…);
        …
     exception
        when Storage_Error => raise Directory_Full;
     end Insert;
     
     procedure Lookup (Given_Name  : in  Name;
                       Corr_Number : out Number)
     isbeginif not Found then
           raise Name_Absent;
        end if;
        …
     end Lookup;
  
  end 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:

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

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

  ...
  exception
     when Line_Failed =>
        begin -- attempt recovery
           Log_Error;
           Retransmit (Current_Packet);
        exception
           when Line_Failed =>
              Notify_Engineer; -- recovery failed!
              Abandon_Call;
        end;
  ...

Information about an exception occurrence

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

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

with Ada.Exceptions;  use Ada.Exceptions;
...
exception
  when Error: High_Pressure | High_Temperature =>
    Put ("Exception: ");
    Put_Line (Exception_Name (Error));
    Put (Exception_Message (Error));
  when Error: others =>
    Put ("Unexpected exception: ");
    Put_Line (Exception_Information(Error));
end;

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.

declare
   Valve_Failure : exception;
begin
  ...
  Raise_Exception (Valve_Failure'Identity, "Failure while opening");
  ...
  Raise_Exception (Valve_Failure'Identity, "Failure while closing");
  ...
exception
  when Fail: Valve_Failure =>
    Put (Exception_Message (Fail));
end;


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

-- This language feature is only available from Ada 2005 on.
declare
   Valve_Failure : exception;
begin
  ...
  raise Valve_Failure with "Failure while opening";
  ...
  raise Valve_Failure with "Failure while closing";
  ...
exception
  when Fail: Valve_Failure =>
    Put (Exception_Message (Fail));
end;

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

See also

Wikibook

Ada 95 Reference Manual

Ada 2005 Reference Manual

Ada Quality and Style Guide


This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.