Skip to content
LumenaryAcademy
Foundations 55 min

Procedures, functions and exceptions

Subprograms whose parameters say which way data flows, expression functions and overloading, and exceptions for the things that go wrong.

Code tested · 3AI-draftedAwaiting review by a computer scientist

Your guides: Chloe · The Designer, Margaret · The Profiler, Gideon · The Language Lawyer

MotivationH

Saying which way the data flows

In C, a function that needs to give back two results takes pointers: void divide(int a, int b, int *q, int *r). Reading the declaration, you cannot tell whether q is read, written or both, or whether it may be null. In Java you would return a small object or an array; in Python, a tuple. Each language has its convention, and each convention leaves something unsaid.

Ada's answer is to make the direction of every parameter part of the subprogram's declaration. A parameter is in (the subprogram reads it), out (the subprogram writes it) or in out (it reads and updates it). The compiler enforces the modes: assigning to an in parameter is an error, and passing a constant where an out parameter is expected is an error too. The declaration therefore tells a reader, and every tool that analyses the code, exactly what a call can change. Later in this course you will see SPARK use those modes to prove that a subprogram reads and writes only what it says it does.

The second half of this lesson is about what happens when a subprogram cannot do its job. You have already met Constraint_Error. Now you will declare your own exceptions, give them messages, catch them where you can do something useful, and learn from a famous accident where an exception was raised correctly and handled disastrously.

DefinitionsH

Procedures, functions and parameter modes

Definition— Procedure and function

A procedure is a subprogram called as a statement; it does something and returns no value. A function is called inside an expression and returns exactly one value of its declared type. Together they are called subprograms.

ModeInside the subprogramAt the callTypical use
in (the default)a constant: readable, never assignableany expressioninputs
outassignable; starts with no meaningful valuea variableresults
in outreadable and assignablea variable, whose value goes in and comes backupdating something

Modes describe what a subprogram may do, not how the value travels. The standard says scalars (integers, enumerations, floats) are always passed by copy, tagged and limited types always by reference, and leaves everything else, such as arrays and records, to the compiler, which passes large objects by reference because it is cheaper. You never write & or * to get efficient passing, and you should never write code whose result depends on which mechanism was chosen.

Since Ada 2012, functions may have out and in out parameters too, but most Ada programmers keep functions free of side effects and use procedures when something must change. SPARK goes further and forbids side effects in functions entirely.

Other features you will use constantly:

  • Named association: Divide (Dividend => 47, Divisor => 5, …) names each parameter, so the order no longer matters and the call documents itself. You can start positionally and switch to named, but not the other way round.
  • Default values: a parameter declared Currency : String := "EUR" may be left out of a call.
  • Overloading: two subprograms may share a name if their parameter or result types differ. The compiler picks the one that fits, and reports an ambiguity rather than guessing if two fit.
  • Expression functions (Ada 2012): a function whose body is one expression, written function Square (X : Integer) return Integer is (X * X);. They pair naturally with if expressions and case expressions, which choose a value rather than a statement.
  • Nesting: subprograms may be declared inside other subprograms, where they can see the enclosing subprogram's parameters and variables.
Worked examplesH

Subprograms in practice

Modes, names and defaults

ada
pragma Ada_2022;
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is

   --  in: read only.  out: written by the callee.  in out: read and updated.
   procedure Divide (Dividend, Divisor : in Natural;
                     Quotient, Remainder : out Natural) is
   begin
      Quotient  := Dividend / Divisor;
      Remainder := Dividend rem Divisor;
   end Divide;

   procedure Swap (A, B : in out Integer) is
      Old_A : constant Integer := A;
   begin
      A := B;
      B := Old_A;
   end Swap;

   function Average (A, B : Integer) return Float is
   begin
      return (Float (A) + Float (B)) / 2.0;
   end Average;

   procedure Show_Price (Amount   : Natural;
                         Currency : String  := "EUR";
                         Show_Tax : Boolean := False) is
   begin
      Put (Currency & Amount'Image);
      if Show_Tax then
         Put (" (tax included)");
      end if;
      New_Line;
   end Show_Price;

   Q, R : Natural;
   X : Integer := 3;
   Y : Integer := 8;
begin
   Divide (Dividend => 47, Divisor => 5, Quotient => Q, Remainder => R);
   Put_Line ("47 = 5 *" & Q'Image & " +" & R'Image);

   Swap (X, Y);
   Put_Line ("X =" & X'Image & ", Y =" & Y'Image);

   Put_Line ("Average of 3 and 8:" & Average (3, 8)'Image);

   Show_Price (120);
   Show_Price (4_500, "INR");
   Show_Price (99, Show_Tax => True);
end Main;

It prints:

text
47 = 5 * 9 + 2
X = 8, Y = 3
Average of 3 and 8: 5.50000E+00
EUR 120
INR 4500
EUR 99 (tax included)

The parameter list of Divide groups names that share a type and mode, and separates groups with semicolons. String parameters such as Currency accept strings of any length; Lesson 4 explains how. The last call skips Currency but gives Show_Tax by name, which is the usual way to set one option among several defaults.

Had Swap declared its parameters with mode in, the assignment A := B; would be rejected. GNAT 14's message, for a procedure that assigns to an in parameter, is:

text
main.adb:5:44: error: assignment to "in" mode parameter not allowed

Expression functions, overloading and recursion

ada
pragma Ada_2022;
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   type Grade is (Fail, Pass, Merit, Distinction);

   --  Expression functions: the body is a single expression.
   function Gcd (A, B : Natural) return Natural is
     (if B = 0 then A else Gcd (B, A mod B));

   function Classify (Score : Natural) return Grade is
     (case Score is
         when 0 .. 39   => Fail,
         when 40 .. 59  => Pass,
         when 60 .. 69  => Merit,
         when others    => Distinction);

   --  Overloading: the same name, told apart by parameter types.
   function Describe (G : Grade) return String is
     (case G is
         when Fail        => "not yet",
         when Pass        => "pass",
         when Merit       => "merit",
         when Distinction => "distinction");

   function Describe (Score : Natural) return String is
     ("Score" & Score'Image & ": " & Describe (Classify (Score)));

   --  A recursive function with a nested helper.
   function Digit_Sum (N : Natural) return Natural is
      function Last_Digit (M : Natural) return Natural is (M mod 10);
   begin
      if N < 10 then
         return N;
      else
         return Last_Digit (N) + Digit_Sum (N / 10);
      end if;
   end Digit_Sum;
begin
   Put_Line ("gcd (84, 36) =" & Gcd (84, 36)'Image);
   Put_Line (Describe (72));
   Put_Line (Describe (38));
   Put_Line (Describe (Merit));
   Put_Line ("Digit sum of 2026:" & Digit_Sum (2026)'Image);
end Main;

It prints:

text
gcd (84, 36) = 12
Score 72: distinction
Score 38: not yet
merit
Digit sum of 2026: 10

Gcd is Euclid's algorithm in one line: the greatest common divisor of A and B equals that of B and A mod B, and the gcd of A and 0 is A. The case expression in Classify must cover every possible Natural, which is why its last choice is others; on the enumeration Grade, by contrast, Describe lists every value and needs no others. The two Describe functions are told apart by their parameter types, so Describe (72) and Describe (Merit) call different functions. And Digit_Sum is recursive: each call handles the last digit and passes the rest on, until a single digit remains.

Expression functions are a matter of taste and size. Professionals use them for short, pure computations, especially in package specifications, where they double as documentation of what a function returns. Anything with loops or several steps gets an ordinary body.

ComputationC

Exceptions

Definition— Exception

An exception is a named error condition. Raising it abandons the current sequence of statements; the run-time system then looks for a handler for it in the current subprogram or block, and if there is none, in the caller, and the caller's caller, and so on. This search is called propagation. If no handler is found, the program stops with a message.

The language predefines a few exceptions: Constraint_Error (a range, index, overflow, division-by-zero or null check failed), Program_Error (for example, a function reached its end without returning), Storage_Error (out of memory or stack) and Tasking_Error (Lesson 8). The input/output packages add Data_Error, End_Error and others. You declare your own like a variable, with the type replaced by the word exception.

Handlers go at the end of any begin … end frame (a subprogram body or a block), after the word exception. Each when names one or more exceptions, when others catches everything else, and E : Some_Error gives a name to the occurrence so that Ada.Exceptions can tell you its name and message.

ada
pragma Ada_2022;
with Ada.Text_IO;    use Ada.Text_IO;
with Ada.Exceptions; use Ada.Exceptions;

procedure Main is
   type Percent is range 0 .. 100;

   Bad_Reading : exception;    -- our own exception

   --  Turn a sensor's text into a humidity percentage.
   function Parse_Humidity (Text : String) return Percent is
      Value : Integer;
   begin
      Value := Integer'Value (Text);          -- may raise Constraint_Error
      if Value not in 0 .. 100 then
         raise Bad_Reading with "humidity" & Value'Image & "% is impossible";
      end if;
      return Percent (Value);
   end Parse_Humidity;

   procedure Report (Text : String) is
   begin
      Put_Line ("""" & Text & """ ->" & Parse_Humidity (Text)'Image & "%");
   exception
      when E : Bad_Reading =>
         Put_Line ("""" & Text & """ rejected: " & Exception_Message (E));
      when Constraint_Error =>
         Put_Line ("""" & Text & """ is not a number");
   end Report;
begin
   Report ("64");
   Report (" 7 ");
   Report ("140");
   Report ("sixty");
   Report ("");

   --  An exception that no handler in Report catches travels outward.
   declare
      Total : Percent := 90;
   begin
      Total := Total + Parse_Humidity ("20");
      Put_Line ("Total:" & Total'Image);
   exception
      when E : others =>
         Put_Line ("Caught " & Exception_Name (E) & " in Main");
   end;
end Main;

It prints:

text
"64" -> 64%
" 7 " -> 7%
"140" rejected: humidity 140% is impossible
"sixty" is not a number
"" is not a number
Caught CONSTRAINT_ERROR in Main

Follow each call. " 7 " is accepted because 'Value ignores leading and trailing spaces. "140" passes 'Value but fails our own check, so Parse_Humidity raises Bad_Reading with a message; the exception propagates out of Parse_Humidity into Report, whose handler prints the message. "sixty" and the empty string make Integer'Value raise Constraint_Error, also handled in Report. In the last block, Parse_Humidity ("20") succeeds, but 90 + 20 does not fit in Percent, so the addition raises Constraint_Error, caught by the block's others handler. (Inside a string literal, "" stands for one quotation mark.)

Two rules are worth stating plainly. A handler does not resume the code that raised: once Report's handler runs, Report is finished. And if nothing handles an exception, it reaches the environment and ends the program with a message and a non-zero exit status. Here is a loop that pushes a Percent past 100, with nothing to catch the error; GNAT 14's run-time printed this and the program exited with status 1:

text
raised CONSTRAINT_ERROR : main.adb:8 range check failed

The message names the exception, the file and line, and which check failed. That is often enough to find a bug without a debugger.

History & global context

Case study: Ariane 5 Flight 501

On 4 June 1996, the first Ariane 5 launcher veered off course about 37 seconds after lift-off and was destroyed. The inquiry board, chaired by the mathematician Jacques-Louis Lions, traced the failure to the inertial reference system, whose software was written in Ada and largely reused from Ariane 4.

One routine converted a 64-bit floating-point value, related to the rocket's horizontal velocity, to a 16-bit signed integer. On Ariane 4's trajectory the value always fitted. Ariane 5 flew a faster trajectory, the value grew too large, and the conversion raised an exception, exactly as the language specifies. The conversion had been left unprotected on purpose: an analysis for Ariane 4 had shown the value could not overflow, and the processor's workload had to stay low. The system's policy for any unexpected exception was to record the failure and shut the computer down, on the assumption that exceptions came from hardware faults that a backup unit would cover. But the backup ran the same software, had already failed the same way, and the main flight computer then interpreted diagnostic data as flight data. Worse still, the routine served no purpose after lift-off; it was kept running for reasons that applied only to Ariane 4.

The lessons professionals draw are not about Ada's syntax. The run-time check worked: it detected a value that did not fit. What failed was the reasoning around it. Reused code carried assumptions about its environment that nobody re-checked, the handling policy treated a software error as a hardware fault, and redundancy with identical software gave no protection against a software error. Today, high-integrity projects respond in exactly the ways this course will show: they write assumptions down as types and contracts so that they travel with the code, and with SPARK they prove that conversions like this one cannot overflow on any input that the contracts allow.

Common misconceptionsH

Common misunderstandings

Misconception

"An out parameter is a pointer." Modes say what may happen to a parameter, not how it is passed. A scalar out parameter is copied back when the subprogram returns; a large array may be passed by reference. Your program must not depend on which, for instance by passing the same variable as two different in out parameters.

Misconception

"An exception handler fixes the error and carries on." A handler replaces the rest of its frame. To retry, put the call inside a loop, with the handler in a block inside the loop.

Misconception

"when others => null; is a safe default." It swallows every error, including ones you never imagined, and the program carries on with wrong data. Handle the exceptions you can do something about; let the others propagate to a place that can log them and fail cleanly.

Misconception

"Exceptions are for normal control flow, like reaching the end of a list." They are for failures. A function that searches a table and may find nothing should say so in its result (Lesson 4 shows how); exceptions are for when a precondition of the program's design has been broken.

Exercises

Exercises

All outputs below were checked by compiling and running the code with GNAT 14.

1. Procedures, functions and exceptions

Warm-upHuman

A procedure Calibrate receives a sensor reading, corrects it using a stored offset, and gives the corrected value back in the same variable. Which mode should its parameter have?

Choose one

2. Procedures, functions and exceptions

CoreComputational

Using the lesson's Divide, what does this print?

Divide (Divisor => 7, Dividend => 30, Remainder => R, Quotient => Q);
Put_Line (Q'Image & R'Image);

3. Procedures, functions and exceptions

Warm-upComputational

In the expression-function program, what does Put_Line (Describe (55)); print?

4. Procedures, functions and exceptions

CoreComputational

What does Gcd (270, 192) return?

5. Procedures, functions and exceptions

StretchComputational

In the humidity program, what line does Report ("-5"); print? Type it exactly, quotation marks included.

6. Procedures, functions and exceptions

CoreHuman

A procedure body contains three statements, S1; S2; S3, and a handler for Constraint_Error. S2 raises Constraint_Error, and the handler prints a message. What happens next?

Choose one

7. Procedures, functions and exceptions

CoreHuman

Which statement best describes the software failure behind Ariane 5 Flight 501 in 1996?

Choose one

8. Procedures, functions and exceptions

Warm-upComputational

What does Digit_Sum (99_999) return?

Further reading and resources