Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 36 ยท Exceptions and Contracts

Exceptions in Ada

Learn Ada exceptions: predefined ones like Constraint_Error, declaring your own, raise, exception handlers, re-raising and exception messages, with C stand-ins.

Things go wrong at run time: an array index is out of range, a file is missing, a value falls outside its type. Ada handles these situations with exceptions. When a problem is detected, an exception is raised, normal execution stops, and control jumps to the nearest matching handler. If none exists in the current subprogram, the exception travels up to the caller, and so on, until a handler is found or the program ends.

The Ada code here is read-only on this site (no Ada compiler runs here). Runnable examples are C stand-ins that imitate the control flow with error codes and setjmp/longjmp, and are labelled as such.

Predefined exceptions

The language defines a handful that the runtime raises for you:

Exception Typical cause
Constraint_Error value outside a subtype range, index out of bounds, division by zero, null dereference
Program_Error a language rule violated at run time (e.g. function ends without return)
Storage_Error out of memory or stack
Tasking_Error communication with a terminated task
ADA
with Ada.Text_IO; use Ada.Text_IO;

procedure Demo is
   subtype Percent is Integer range 0 .. 100;
   P : Percent;
   N : Integer := 150;
begin
   P := N;                       --  raises Constraint_Error
   Put_Line ("not reached");
exception
   when Constraint_Error =>
      Put_Line ("value out of range");
end Demo;

This prints value out of range. The assignment violates the subtype, and the check is part of the language, not an optional library test. (A compiler may suppress checks if you ask it to; see the chapter on proving their absence.)

Your own exceptions

Declare an exception like an object and raise it with raise:

ADA
Stack_Empty : exception;

procedure Pop (S : in out Stack; X : out Integer) is
begin
   if S.Top = 0 then
      raise Stack_Empty with "pop on empty stack";
   end if;
   X := S.Items (S.Top);
   S.Top := S.Top - 1;
end Pop;

raise ... with "text" attaches a message. A handler can read it with Ada.Exceptions.Exception_Message (E) after naming the occurrence: when E : Stack_Empty =>. Exception_Information (E) gives a longer string, including the name and often a traceback.

Exception flow

Raise problem detected
Handler search this block, then caller
Handle recover or clean up
Unhandled task or program ends

Handlers sit at the end of any block.

1 / 2

Handlers

Any begin ... end block, subprogram body or task body may end with an exception part. Handlers are tried top to bottom, and when others catches everything not listed.

ADA
begin
   Process (Data);
exception
   when Constraint_Error | Data_Error =>
      Put_Line ("bad data, skipping");
   when Stack_Empty =>
      Put_Line ("nothing to do");
   when E : others =>
      Put_Line ("unexpected: " & Ada.Exceptions.Exception_Name (E));
      raise;                     --  re-raise the same exception
end;

A bare raise; inside a handler re-raises the exception being handled, which is the usual way to log and let the caller decide. A handler replaces the rest of the block it belongs to: after the handler finishes, the block is considered complete and execution continues after its end, with no way to "resume" at the failing statement.

Be careful with when others: swallowing every exception silently hides real bugs. Handle specific exceptions you can recover from, and let the rest propagate.

Stand-in: error codes versus jumps (C, runnable)

C has no exceptions, but setjmp/longjmp give the same shape: jump to a recovery point from deep inside a call chain. The program below raises "Stack_Empty" from pop and handles it at the caller. This is a teaching stand-in only; Ada's mechanism also runs finalization on the way out, which longjmp does not.

C C stand-in: raise and handle with setjmp

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: propagation through callers (C, runnable)

Here the failure starts three calls deep. No intermediate function checks anything, yet the handler in main still sees it, which is the benefit of propagation over checking an error code after every call.

C C stand-in: propagation across calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Good habits

  • Raise exceptions for conditions the caller cannot reasonably avoid; for conditions a caller can check beforehand, prefer preconditions.
  • Keep handlers close to code that knows how to recover.
  • In a task, an unhandled exception ends that task silently: add a last-resort handler that reports it.
  • Re-raise with raise; after logging, or raise a more meaningful exception with context.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which predefined exception is raised when you assign 150 to a variable of subtype Integer range 0 .. 100?

    Range violations of a subtype raise Constraint_Error.
  2. 2. What does a bare raise; inside a handler do?

    It propagates the same exception occurrence to the caller.
  3. 3. After a handler finishes, where does execution continue?

    Ada has termination semantics: the block is abandoned, there is no resumption.
  4. 4. Why is when others => null; considered dangerous?

    A catch-all that does nothing hides real bugs.

Summary

  • Exceptions signal run-time problems; predefined ones include Constraint_Error and Program_Error.
  • Declare your own with name : exception; and raise with raise Name with "message";.
  • Handlers live in exception parts of blocks, subprograms and tasks; when others is a catch-all.
  • Ada uses termination semantics: the failing block ends and the exception propagates to the caller.
  • The C examples use setjmp/longjmp as a rough stand-in only.

Next: Propagation, Cleanup and Finalization