Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 36 ยท Exceptions and Contracts

Propagation, Cleanup and Finalization

How Ada exceptions propagate through subprograms, tasks and declarations, how to release resources safely, and how Controlled types finalize objects, with C stand-ins.

Raising and catching an exception is the easy half. The harder half is leaving a program in a sane state: files closed, locks released, memory freed, even though a routine was abandoned halfway. This lesson covers how an exception travels, what happens when it escapes from odd places such as declarations and tasks, and the patterns Ada gives you for cleanup.

Ada code in this lesson is read-only on this site. The C stand-ins are runnable and show the idea with explicit cleanup functions.

The propagation path

When no handler in the current frame matches, the frame is abandoned and the exception is raised again at the point of the call in the caller. Local objects in the abandoned frame cease to exist. The search stops at the first frame with a matching handler. If it reaches the main subprogram unhandled, the program ends and the runtime prints the exception name and message.

Two special cases surprise beginners:

  1. Exceptions in declarations. If elaborating a declaration raises, for example X : Positive := Compute; raising Constraint_Error, the handler in the same body does not catch it. The exception goes to the caller. Put risky initialization in the begin part, or wrap it in a nested block.
  2. Exceptions in a handler. A new exception raised inside a handler also leaves the current frame; it is not caught by sibling handlers.
ADA
procedure Outer is
   procedure Inner is
      X : Positive := Compute_Bad_Value;    --  raises here
   begin
      null;
   exception
      when Constraint_Error =>              --  does NOT catch the line above
         Put_Line ("never printed");
   end Inner;
begin
   Inner;
exception
   when Constraint_Error =>
      Put_Line ("caught in Outer");         --  this one runs
end Outer;

Tasks and exceptions

An exception that escapes a task body does not propagate to the code that created the task, because they run concurrently. The task simply terminates, silently by default. A task body should therefore end with a handler that reports the failure, or signals a supervisor through a protected object. A failed rendezvous is different: if the called task raises inside an accept body, the exception is raised in both the called task and the caller; and calling an entry of a terminated task raises Tasking_Error in the caller.

Where exceptions go

Subprogram up to the caller
Task body task just ends
Accept body both sides see it
Declaration caller, not own handler

Know where yours will land.

1 / 2

Cleanup with handlers

The classic pattern is "acquire, use, release, even on failure":

ADA
procedure Process (Name : String) is
   File : Ada.Text_IO.File_Type;
begin
   Ada.Text_IO.Open (File, Ada.Text_IO.In_File, Name);
   begin
      Work (File);
   exception
      when others =>
         Ada.Text_IO.Close (File);
         raise;                       --  clean up, then pass it on
   end;
   Ada.Text_IO.Close (File);
end Process;

Writing this at every use site is tedious and error-prone, which is why Ada has a second tool.

Controlled types and Finalize

A type derived from Ada.Finalization.Limited_Controlled can override Finalize. The runtime calls it when an object goes out of scope, whether the scope ended normally or by an exception. That makes it the Ada equivalent of RAII destructors.

ADA
with Ada.Finalization;

type Guard is new Ada.Finalization.Limited_Controlled with record
   Name : access constant String;
end record;

overriding procedure Finalize (G : in out Guard) is
begin
   Put_Line ("releasing " & G.Name.all);
end Finalize;

Declare a Guard at the top of a subprogram and its Finalize runs when the subprogram is left in any way. A Finalize procedure must not itself let an exception escape: if it does, the runtime raises Program_Error. Keep it simple, use it for closing handles and releasing locks, and prefer it to scattering handlers.

For protected objects and tasks, locks are released automatically when an exception leaves a protected operation, so you do not clean up there.

Stand-in: cleanup on every path (C, runnable)

C has no destructors, but GCC supports __attribute__((cleanup(fn))), which calls fn when a variable leaves scope. This stand-in is the closest runnable equivalent to Finalize: it runs on a normal return and on an early return out of a nested call.

C C stand-in: cleanup attribute as Finalize

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: nested resources release in reverse (C, runnable)

Objects finalize in the reverse order of declaration. The same rule applies to the cleanup attribute.

C C stand-in: reverse-order release

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.

The expected output has the release lines in the order lock, file, database.

Practical advice

  • Put initialization that can fail in the body, not in declarations, so your own handler sees it.
  • Give every task a final handler.
  • Use controlled types for files, locks and memory instead of hand-written cleanup at each call.
  • Remember that exceptions are for exceptional cases; in tight, well-understood code, contracts catch mistakes earlier.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A declaration in a subprogram raises Constraint_Error during elaboration. Where is it handled?

    Handlers of a body do not cover its own declarative part; the exception goes to the caller.
  2. 2. What happens to an exception that escapes a task body?

    Tasks run concurrently with their creators, so the exception cannot propagate to them.
  3. 3. When does Finalize of a controlled object run?

    That is what makes controlled types suitable for cleanup.
  4. 4. In which order are objects finalized when leaving a scope?

    Like stack unwinding, later objects are finalized first.

Summary

  • An unhandled exception leaves the frame and is re-raised in the caller.
  • Exceptions in declarations are not caught by the same body's handlers.
  • Task bodies need their own last-resort handler; failed rendezvous affect both sides.
  • Handlers with raise; support cleanup-then-propagate.
  • Controlled types run Finalize on every exit, in reverse order of declaration.

Next: Preconditions and Postconditions