Implement best practices equivalent to Java finalize blocks in Ada (2005 or 2012)

Java has a finalize block that allows some statements to be executed after the block

try {
  ...
} catch (Exception e) {
  ...
} finally {
  ... // any code here
}

ADA has a controlled object that allows the finalize operation, but it does not have the same finalize block as in Java This is useful for logging, closing files, transactions, etc. (there is no need to create a specific tag type for each possible block)

>How will you implement such a termination block in Ada 2005 (while keeping the code readable)? > Does ADA 2012 have plans to allow easy execution of any end code?

Solution

I believe this code will act according to your requirements; It successfully prints the current filled or returned 42 This is the implementation of t.e.d. recommendations

On Mac OS X, Darwin 10.6 GCC 4.5.1 is used on 0 0 to test

with Ada.Finalization;
package Finally is

   --  Calls Callee on deletion.
   type Caller (Callee : not null access procedure)
      is new Ada.Finalization.Limited_Controlled with private;

private

   type Caller (Callee : not null access procedure)
      is new Ada.Finalization.Limited_Controlled with null record;

   procedure Finalize (Object : in out Caller);

end Finally;


package body Finally is

   procedure Finalize (Object : in out Caller)
   is
   begin
      Object.Callee.all;
   end Finalize;

end Finally;


with Ada.Text_IO; use Ada.Text_IO;
with Finally;
procedure Finally_Demo is
begin

   declare

      X : Integer := 21;

      --  The cleanup procedure,to be executed when this block is left
      procedure F
      is
      begin
         Put_Line ("X is " & Integer'Image (X));
      end F;

      --  The controlled object,whose deletion will execute F
      F_Caller : Finally.Caller (F'Access);

   begin

      X := 42;

      raise Constraint_Error;

   end;

end Finally_Demo;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>