ZetCode

Ada exceptions

last modified November 23, 2026

An exception is a named condition that interrupts the normal flow of a program. Ada uses exceptions for errors detected by the language itself, such as an out-of-range assignment or a division by zero, and for errors that a program detects and reports on its own. A block of statements may carry a handler that names the exceptions it can deal with; if no handler matches, the exception propagates to the caller. This article shows how to declare, raise, catch, inspect, and propagate exceptions.

Raising and handling an exception

An exception is declared like a constant, with the reserved word exception instead of a type. The statement raise takes its name and transfers control out of the current sequence of statements. The handler at the end of the procedure body decides what happens next.

first_exception.adb
with Ada.Text_IO;
use Ada.Text_IO;

procedure First_Exception is
   Bad_Value : exception;
begin
   Put_Line ("before the raise");
   raise Bad_Value;
exception
   when Bad_Value =>
      Put_Line ("Bad_Value was raised");
end First_Exception;

The first Put_Line runs, then raise abandons the rest of the sequence and searches for a handler. The handler for Bad_Value is part of the same procedure body, so it runs and the procedure ends normally. Any statements between the raise and the handler would be skipped.

$ gnatmake -gnat2022 -gnatwa first_exception.adb
$ ./first_exception
before the raise
Bad_Value was raised

An exception raised by the run time

Most exceptions in a working program are raised by checks that the compiler inserts. Dividing an integer by zero, indexing outside an array, assigning a value outside a subtype's range, and dereferencing a null access value all raise Constraint_Error. The following program performs a valid division and then an invalid one; the handler covers both calls.

divide_demo.adb
with Ada.Text_IO;
use Ada.Text_IO;

procedure Divide_Demo is
   function Divide (A, B : Integer) return Integer is
   begin
      return A / B;
   end Divide;

   Divisors : constant array (1 .. 2) of Integer := [2, 0];
begin
   for I in Divisors'Range loop
      Put_Line ("result =" & Integer'Image (Divide (10, Divisors (I))));
   end loop;
exception
   when Constraint_Error =>
      Put_Line ("cannot divide by zero");
end Divide_Demo;

The first iteration prints 5. The second call raises Constraint_Error inside Divide, and the handler at the level of Divide_Demo catches it. Control does not return to the loop after the handler, because the handler belongs to the procedure body as a whole; the procedure goes straight to its end.

$ gnatmake -gnat2022 -gnatwa divide_demo.adb
$ ./divide_demo
result = 5
cannot divide by zero

Several handlers

A block may list a handler for each exception it expects, in any order except that when others must come last. Handlers may also sit inside a loop, so that one bad value does not stop the remaining work. The next program checks four integers, raising a user-defined exception for a negative value and Constraint_Error for one above 100.

handlers.adb
with Ada.Text_IO;
use Ada.Text_IO;

procedure Handlers is
   Bad_Value : exception;

   procedure Check (N : Integer) is
   begin
      if N < 0 then
         raise Bad_Value;
      elsif N > 100 then
         raise Constraint_Error with "too large";
      end if;
      Put_Line ("accepted" & Integer'Image (N));
   end Check;

   Values : constant array (1 .. 4) of Integer := [-1, 50, 101, 0];
begin
   for I in Values'Range loop
      begin
         Check (Values (I));
      exception
         when Bad_Value =>
            Put_Line ("negative" & Integer'Image (Values (I)));
         when Constraint_Error =>
            Put_Line ("out of range" & Integer'Image (Values (I)));
         when others =>
            Put_Line ("unexpected problem");
      end;
   end loop;
end Handlers;

The begin ... exception ... end inside the loop is a block with its own handler. A raise inside Check leaves that procedure and is caught by the block, after which the loop continues with the next value. when others catches any exception that the two earlier handlers do not name, which keeps the program from terminating on an error it did not anticipate.

$ gnatmake -gnat2022 -gnatwa handlers.adb
$ ./handlers
negative-1
accepted 50
out of range 101
accepted 0

Exception names and messages

A handler may name the exception occurrence with a colon and an identifier, as in when E : Bad_Input =>. The package Ada.Exceptions then provides Exception_Name and Exception_Message. The message is the string attached to the raise with the reserved word with.

message_demo.adb
with Ada.Text_IO;
with Ada.Exceptions;
use Ada.Text_IO;

procedure Message_Demo is
   Bad_Input : exception;
begin
   raise Bad_Input with "value must be positive";
exception
   when E : Bad_Input =>
      Put_Line ("name =" & Ada.Exceptions.Exception_Name (E));
      Put_Line ("message =" & Ada.Exceptions.Exception_Message (E));
end Message_Demo;

The name is the fully qualified name of the exception, in upper case: MESSAGE_DEMO.BAD_INPUT. The message is exactly the text given to with, with no added punctuation. Both are useful in a log, because they identify what went wrong without requiring a separate handler for every possible failure.

$ gnatmake -gnat2022 -gnatwa message_demo.adb
$ ./message_demo
name =MESSAGE_DEMO.BAD_INPUT
message =value must be positive

Propagation

An exception that has no matching handler in the current subprogram propagates to its caller, then to that caller's caller, until some handler accepts it or the main program ends. A handler may also re-raise the same occurrence with a bare raise;, after doing some work of its own.

propagate.adb
with Ada.Text_IO;
with Ada.Exceptions;
use Ada.Text_IO;

procedure Propagate is
   Error : exception;

   procedure Inner is
   begin
      raise Error with "raised in Inner";
   end Inner;

   procedure Outer is
   begin
      Inner;
      Put_Line ("not reached");
   exception
      when E : Error =>
         Put_Line ("Outer saw" & Ada.Exceptions.Exception_Message (E));
         raise;
   end Outer;
begin
   Outer;
exception
   when E : Error =>
      Put_Line ("main saw" & Ada.Exceptions.Exception_Message (E));
end Propagate;

Inner raises the exception, and Outer has a handler, so the message is printed once there. The bare raise; sends the same occurrence onward, and the handler in Propagate prints it a second time. Without the final handler the program would terminate with the exception name and message on the standard error stream.

$ gnatmake -gnat2022 -gnatwa propagate.adb
$ ./propagate
Outer sawraised in Inner
main sawraised in Inner

An applied example: checking values

A common use of exceptions is to process a list of records when some records are invalid. The program below holds four fixed-width lines with a name and a price. It converts each price with 'Value; a string that is not a number makes 'Value raise Constraint_Error, which the handler turns into a message while the loop continues.

value_check.adb
with Ada.Text_IO;
use Ada.Text_IO;

procedure Value_Check is
   Data : constant array (1 .. 4) of String (1 .. 9) :=
     ["apple  42", "pear   17", "plum   xx", "kiwi    8"];
begin
   for I in Data'Range loop
      declare
         Name  : constant String := Data (I) (1 .. 5);
         Price : Integer;
      begin
         Price := Integer'Value (Data (I) (6 .. 9));
         Put_Line (Name & "=" & Integer'Image (Price));
      exception
         when Constraint_Error =>
            Put_Line (Name & " has a bad price");
      end;
   end loop;
end Value_Check;

Each iteration has a declare block with its own handler, so only the conversion of the current line is protected. The name is sliced out before the conversion, which means it is still available in the handler. The text input routines of Ada.Text_IO report a malformed number with Data_Error instead; that exception is covered in the article on reading input.

$ gnatmake -gnat2022 -gnatwa value_check.adb
$ ./value_check
apple= 42
pear = 17
plum  has a bad price
kiwi = 8

Next steps

The next article turns to output formatting. It shows how Ada.Text_IO places integers, reals, and enumeration values in columns, and how Integer_IO, Float_IO, and Enumeration_IO control width, precision, and case.

Source

Ada Reference Manual

GNAT User's Guide

AdaCore learning resources

In this article we have declared and raised exceptions, caught Constraint_Error from a run-time check, listed several handlers with when others, read an exception's name and message, propagated an occurrence through two subprograms and re-raised it, and recovered from a bad conversion inside a loop. The access types article shows a null dereference, one of the checks that raises Constraint_Error.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Ada tutorials.