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;
解决方案
您需要在调用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;
推荐阅读
- scala - 在 scala.concurrent.Future 中包含 .futureValue 方法?
- android - opengl-es 前置像素光照问题
- java - 在休眠中尝试从与 cascadeType.ALL 的 OneToMany 关系中删除时获取参照完整性约束违规
- spring - Spring Boot DB连接释放方式
- ruby-on-rails - 无法将数据从控制器传递到视图
- asp.net-core - 如何从 Ajax 中的数据库中删除?
- javascript - SlickR Shiny R 在通过用户输入过滤轮播 obj 时将点动态转换为图像
- c# - 如何使用此代码使用停止按钮在 backgroundWorker 中停止 webDriver?
- swift - 将场景重新定位到视图顶部
- python-3.x - Python3 SMTP SSL 证书更新 - SSL:CERTIFICATE_VERIFY_FAILED 无法获取本地颁发者证书(_ssl.c:1108)