首页 > 解决方案 > 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;

标签: exceptionada

解决方案


您需要在调用Bar. 另请参阅learn.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;

推荐阅读