Custom Errors in Ada

Our first example demonstrates how to create custom error types in Ada. This is similar to implementing the Error() method in other languages.

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;

procedure Custom_Errors is
   -- A custom error type usually has the suffix "Error".
   type Arg_Error is record
      Arg     : Integer;
      Message : Unbounded_String;
   end record;

   -- Define an exception for our custom error
   Arg_Error_Exception : exception;

   -- Function to raise our custom error
   function F (Arg : Integer) return Integer is
   begin
      if Arg = 42 then
         -- Raise our custom exception with the error details
         raise Arg_Error_Exception with 
           Integer'Image(Arg) & " - " & To_String(To_Unbounded_String("can't work with it"));
      end if;
      return Arg + 3;
   end F;

begin
   declare
      Result : Integer;
   begin
      Result := F(42);
      Put_Line("Result: " & Integer'Image(Result));
   exception
      when Arg_Error_Exception =>
         -- Extract the error message
         declare
            Error_Message : String := Exception_Message(Arg_Error_Exception'Identity);
         begin
            Put_Line("Caught Arg_Error:");
            Put_Line(Error_Message);
         end;
   end;
end Custom_Errors;

In this Ada example, we define a custom error type Arg_Error as a record. We also define an exception Arg_Error_Exception to represent our custom error condition.

The F function demonstrates how to raise our custom exception when a specific condition is met (in this case, when the argument is 42).

In the main procedure, we call F with the argument 42 and handle the potential exception. If an Arg_Error_Exception is raised, we catch it and print the error message.

To run this program:

$ gnatmake custom_errors.adb
$ ./custom_errors
Caught Arg_Error:
42 - can't work with it

This example shows how Ada handles custom errors through exceptions, which is a bit different from the error interface approach in some other languages. However, it allows for similar functionality in terms of creating and handling custom error types.