Recover in Ada
Ada provides a mechanism to handle exceptions, which are similar to panics in other languages. The raise
statement is used to raise an exception, and the exception
block is used to catch and handle exceptions.
with Ada.Text_IO;
use Ada.Text_IO;
procedure Recover is
-- This procedure raises an exception
procedure May_Raise_Exception is
begin
raise Constraint_Error with "a problem";
end May_Raise_Exception;
begin
-- The exception handling must be done within the same procedure
-- or a caller of the procedure that might raise an exception
begin
May_Raise_Exception;
-- This code will not run, because May_Raise_Exception raises an exception.
-- The execution stops at the point of the exception and resumes in the exception handler.
Put_Line("After May_Raise_Exception");
exception
when E : others =>
-- The Exception_Message function returns the message associated with the exception
Put_Line("Recovered. Error:");
Put_Line(Ada.Exceptions.Exception_Message(E));
end;
end Recover;
In Ada, exceptions are used for error handling and recovery. The raise
statement is used to raise an exception, which is similar to panic in other languages. The exception
block is used to catch and handle exceptions, which is analogous to recover.
In this example, we define a procedure May_Raise_Exception
that raises a Constraint_Error
exception with a custom message. In the main procedure, we call May_Raise_Exception
within a block that has an exception handler.
If an exception is raised, the execution immediately jumps to the exception handler. The handler catches all exceptions (when others =>
), retrieves the exception message using Ada.Exceptions.Exception_Message
, and prints it.
To run this Ada program:
$ gnatmake recover.adb
$ ./recover
Recovered. Error:
a problem
This demonstrates how Ada can recover from exceptions, allowing a program to handle errors gracefully and continue execution instead of terminating abruptly.