Panic in Ada

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Exceptions; use Ada.Exceptions;

procedure Main is

   procedure Raise_Exception is
   begin
      raise Constraint_Error with "a problem";
   end Raise_Exception;

   procedure Create_File is
      F : File_Type;
   begin
      Create (F, Out_File, "/tmp/file");
      Close (F);
   exception
      when E : others =>
         raise Constraint_Error with "Failed to create file: " & Exception_Message(E);
   end Create_File;

begin
   -- We'll use exceptions throughout this site to check for
   -- unexpected errors. This is the only program on the
   -- site designed to raise an exception.
   Raise_Exception;

   -- A common use of exceptions is to abort if a procedure
   -- encounters an error that we don't know how to
   -- (or want to) handle. Here's an example of
   -- raising an exception if we get an unexpected error when creating a new file.
   Create_File;

exception
   when E : others =>
      Put_Line ("Exception: " & Exception_Name(E) & " - " & Exception_Message(E));
      Set_Exit_Status (Failure);
end Main;

This Ada program demonstrates the use of exceptions, which are similar to panics in some ways. Here’s a breakdown of the translation:

  1. We import necessary Ada packages for input/output and exception handling.

  2. The Raise_Exception procedure simulates the panic("a problem") call in the original code.

  3. The Create_File procedure attempts to create a file, and raises an exception if it fails, similar to the file creation attempt in the original code.

  4. In the main procedure, we call Raise_Exception first, which will cause the program to terminate with an exception.

  5. We then have the Create_File call, which won’t be reached due to the previous exception, similar to the original code.

  6. The exception handler at the end catches any unhandled exceptions, prints the exception name and message, and sets the exit status to failure.

To run this program:

$ gnatmake main.adb
$ ./main
Exception: CONSTRAINT_ERROR - a problem

Running this program will cause it to raise an exception, print an error message, and exit with a non-zero status.

When the first exception in Main is raised, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the Raise_Exception call.

Note that unlike some languages which use return codes for error handling, in Ada it is idiomatic to use exceptions for handling many errors, similar to the example shown here.