ADA:如何捕获对象实例化期间引发的异常?

Pol*_*015 3 exception ada

在声明部分中实例化对象期间可能会引发异常。

例如,以下代码由于(有意的)堆栈溢出而引发了Storage_Error异常。

如何捕获此异常?

(我尝试将异常处理放入实例化的对象主体以及实例化该过程的过程中,未能捕获实例化期间引发的异常。)

谢谢!

---------------------- foo.ads -----------------------
generic
   Size : Natural;
package Foo is
    type Integer_Array is Array (1..Size) of Integer;
    buffer : Integer_Array;
end Foo;
---------------------- foo.adb -----------------------
With Text_IO; use Text_IO;
package body Foo is
begin
    exception -- Failed attempt 
        when storage_error =>
            Put_line("Foo: Storage Error");
        when others =>
            Put_line("Foo: Other Error");
end Foo;
---------------------- bar.adb -----------------------
with Text_IO; use Text_IO;
With Foo;

procedure Bar is
    package object is new Foo (Size => 10_000_000);
begin
    Put_line("Dummy Statement");
    exception -- Failed attempt as well
    when storage_error =>
        Put_line("Bar: Storage Error");
    when others =>
        Put_line("Bar: Other Error");
end Bar;
Run Code Online (Sandbox Code Playgroud)

Dee*_*Dee 5

您需要在调用的子程序中捕获异常Bar。另请参阅learning.adacore.com上的“ 处理异常”部分中的注意框。注意框中给出的示例的略微修改版本:

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

procedure Be_Careful is

   function Dangerous return Integer is
   begin
      raise Constraint_Error;
      return 42;
   end Dangerous;

begin

   declare
      A : Integer := Dangerous;
   begin
      Put_Line (Integer'Image (A));
   exception
      when Constraint_Error => Put_Line ("missed!");
   end;

exception
   when Constraint_Error => Put_Line ("caught!");
end Be_Careful;
Run Code Online (Sandbox Code Playgroud)