gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:42:30 26 4
gpt4 key购买 nike

在声明部分的对象实例化过程中可能会引发异常。

例如,下面的代码引发了由(故意的)堆栈溢出引起的 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;

最佳答案

你需要在调用Bar的子程序中捕获异常。另见 Handling an Exception 部分中的注意框在 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;

关于exception - ADA:如何捕获对象实例化期间引发的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57947497/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com