\chapter{Exceptions}
\section{Robustness}
\emph{Robustness} is the ability of a system or system component to
behave ``reasonably'' when it detects an anomaly, e.g.:
\begin{itemize}
\item It receives invalid inputs.
\item Another system component (hardware or software) malfunctions.
\end{itemize}
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.
\section{Modules, preconditions and postconditions}
A module may be specified in terms of its preconditions and
postconditions. A \emph{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?
\begin{itemize}
\item Halt? Even with diagnostic information, this is generally
unacceptable.
\item 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.
\item 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.
\item Exception handling --- Ada's solution. A module detecting an
anomaly raises an exception. The same, or another, module may
handle that exception.
\end{itemize}
The exception mechanism permits clean, modular handling of anomalous
situations:
\begin{itemize}
\item 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).
\item A unit may propagate an exception that has been raised by itself
(or propagated out of another unit it has called).
\item A unit may alternatively handle such an exception, allowing
programmer-defined recovery from an anomalous situation. Exception
handlers are segregated from normal-case code.
\end{itemize}
\section{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:
\begin{itemize}
\item \lstinline|Constraint_Error|, raised when a subtype's constraint
is not satisfied
\item \lstinline|Program_Error|, when a protected operation is called
inside a protected object, e.g.
\item \lstinline|Storage_Error|, raised by running out of storage
\item \lstinline|Tasking_Error|, when a task cannot be activated
because the operating system has not enough resources, e.g.
\end{itemize}
Ex.1
\begin{mylstlisting}
Name : String (1 .. 10);
...
Name := "Hamlet"; -- Raises Constraint_Error
-- because the "Hamlet" has bounds (1 .. 6)
\end{mylstlisting}
Ex.2
\begin{mylstlisting}
loop
P := new Int_Node'(0, P);
end loop; -- Soon raises Storage_Error,
-- because of the extreme memory leak.
\end{mylstlisting}
Ex.3 Compare the following approaches:
\begin{mylstlisting}
procedure Compute_Sqrt (X : in Float;
Sqrt : out Float;
OK : out Boolean)
is
begin
if X >= 0 then
OK := True;
-- compute square-root of 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 : 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;
\end{mylstlisting}
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, \emph{ad nauseam}. Compared this to:
\begin{mylstlisting}
function Sqrt (X : Float) return Float is
begin
if X < 0.0 then
raise Constraint_Error;
end if;
-- compute \u221aX
...
end Sqrt;
...
procedure Triangle (A, B, C : in Float;
Area, Perimeter : out Float)
is
S : Float := 0.5 * (A + B + C);
OK : Boolean;
begin
Area := Sqrt (S * (S-A) * (S-B) * (S-C));
Perimeter := 2.0 * S;
end Triangle;
\end{mylstlisting}
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:
\begin{mylstlisting}
subtype Pos_Float is Float range 0.0 .. Float'Last;
function Sqrt (X : Pos_Float) return Pos_Float is
begin
-- compute square root of X
...
end Sqrt;
\end{mylstlisting}
A negative argument to Sqrt now raises Constraint\_Error at the point
of call. Sqrt is never even entered.
\section{Input-output exceptions}
Some examples of exceptions raised by subprograms of the
\emph{predefined package} \lstinline|Ada.Text_IO| are:
\begin{itemize}
\item \lstinline|End_Error|, raised by Get, Skip\_Line, etc., if
end-of-file already reached.
\item \lstinline|Data_Error|, raised by Get in Integer\_IO, etc., if
the input is not a literal of the expected type.
\item \lstinline|Mode_Error|, raised by trying to read from an output
file, or write to an input file, etc
\item \lstinline|Layout_Error|, raised by specifying an invalid data
format in a text I/O operation
\end{itemize}
Ex. 1
\begin{mylstlisting}
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;
\end{mylstlisting}
\section{Exception declarations}
Exceptions are declared rather like objects, but they are not objects.
For example, recursive re-entry to a scope where an exception is
declared does \emph{not} create a new exception of the same name; instead
the exception declared in the outer invocation is reused.
Ex.1
\begin{mylstlisting}
Line_Failed : exception;
\end{mylstlisting}
Ex.2
\begin{mylstlisting}
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;
\end{mylstlisting}
\section{Raising exceptions}
The \lstinline|raise| statement explicitly raises a specified exception.
Ex. 1
\begin{mylstlisting}
package body Directory_Enquiries is
procedure Insert (New_Name : in Name;
New_Number : in Number)
is
...
begin
...
if New_Name = Old_Entry.A_Name then
raise Name_Duplicated;
end if;
...
New_Entry := new Dir_Node'(New_Name, New_Number,\u2026);
...
exception
when Storage_Error => raise Directory_Full;
end Insert;
procedure Lookup (Given_Name : in Name;
Corr_Number : out Number)
is
...
begin
...
if not Found then
raise Name_Absent;
end if;
...
end Lookup;
end Directory_Enquiries;
\end{mylstlisting}
\section{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:
\begin{itemize}
\item by completing;
\item by executing a \lstinline|return| statement;
\item by raising a different exception (\lstinline|raise e;|);
\item by re-raising the same exception (\lstinline|raise;|).
\end{itemize}
Suppose that an exception \lstinline|e| is raised in a sequence of statements
\lstinline|U| (a block, subprogram body, etc.).
\begin{itemize}
\item If \lstinline|U| contains a handler for \lstinline|e|: that
handler is executed, then control leaves \lstinline|U|.
\item If \lstinline|U| contains no handler for \lstinline|e|:
\lstinline|e| is ''propagated'' out of \lstinline|U|; in effect,
\lstinline|e| is raised at the ``point of call'' of \lstinline|U|.
\end{itemize}
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
\begin{mylstlisting}
...
exception
when Line_Failed =>
begin -- attempt recovery
Log_Error;
Retransmit (Current_Packet);
exception
when Line_Failed =>
Notify_Engineer; -- recovery failed!
Abandon_Call;
end;
...
\end{mylstlisting}
\section{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:
\begin{description}
\item [Exception\_Name]: return the full exception name using the dot
notation and in uppercase letters. For example,
\lstinline|Queue.Overflow|.
\item [Exception\_Message]: return the exception message associated
with the occurrence.
\item [Exception\_Information]: return a string including the
exception name and the associated exception message.
\end{description}
For getting an exception occurrence object the following syntax is used:
\begin{mylstlisting}
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;
\end{mylstlisting}
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.
\begin{mylstlisting}
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 (Exceptions_Message (Fail));
end;
\end{mylstlisting}
The package also provides subprograms for saving exception occurrences
and reraising them.
\section{See also}
\subsection{Wikibook}
\subsection{Ada 95 Reference Manual}
\begin{itemize}
\item Section 11: Exceptions \footnote{http://www.adaic.com/standards/95lrm/html/RM-11.html}
\item 11.4.1 The Package Exceptions \footnote{http://www.adaic.com/standards/95lrm/html/RM-11-4-1.html}
\end{itemize}
\subsection{Ada 2005 Reference Manual}
\begin{itemize}
\item Section 11: Exceptions \footnote{http://www.adaic.com/standards/05rm/html/RM-11.html}
\item 11.4.1 The Package Exceptions \footnote{http://www.adaic.com/standards/05rm/html/RM-11-4-1.html}
\end{itemize}
\subsection{Ada Quality and Style Guide}
\begin{itemize}
\item 4.3 Exceptions \footnote{http://www.adaic.com/docs/95style/html/sec\_4/4-3.html}
\item 4.3.1 Using Exceptions to Help Define an Abstraction \footnote{http://www.adaic.com/docs/95style/html/sec\_4/4-3-1.html}
\item 5.8 Using Exceptions \footnote{http://www.adaic.com/docs/95style/html/sec\_5/5-8.html}
\item 5.8.1 Handling Versus Avoiding Exceptions \footnote{http://www.adaic.com/docs/95style/html/sec\_5/5-8-1.html}
\item 5.8.2 Handling for Others \footnote{http://www.adaic.com/docs/95style/html/sec\_5/5-8-2.html}
\item 5.8.3 Propagation \footnote{http://www.adaic.com/docs/95style/html/sec\_5/5-8-3.html}
\item 5.8.4 Localizing the Cause of an Exception \footnote{http://www.adaic.com/docs/95style/html/sec\_5/5-8-4.html}
\item 7.5 Exceptions \footnote{http://www.adaic.com/docs/95style/html/sec\_7/7-5.html}
\item 7.5.1 Predefined and User-Defined Exceptions \footnote{http://www.adaic.com/docs/95style/html/sec\_7/7-5-1.html}
\item 7.5.2 Implementation-Specific Exceptions \footnote{http://www.adaic.com/docs/95style/html/sec\_7/7-5-2.html}
\end{itemize}