捕获前提条件断言失败



我正在尝试捕获main过程中的这个前提条件中的错误,我想知道是否可以捕获?我是否需要将其移动到另一个过程,然后在main中调用它才能捕获它?

with
ada.text_io,
ada.command_line,
ada.strings.bounded,
system.assertions;
procedure main with
pre => (ada.command_line.argument_count > 2)
is
package b_str is new
ada.strings.bounded.generic_bounded_length (max => 255);
use b_str;
input_file : bounded_string;
argument : bounded_string;
i : integer := 1;
begin
while i <= ada.command_line.argument_count loop
argument := to_bounded_string(
ada.command_line.argument(i)
);
ada.text_io.put_line("[" & i'image & "] "
& to_string(argument)
);
i := i + 1;
end loop;
exception
when system.assertions.assert_failure =>
ada.text_io.put_line("Failed precondition");
end main;

我找到了答案:

异常处理程序有一个需要注意的重要限制:声明性部分中引发的异常不会被该块的处理程序捕获。

发件人:https://learn.adacore.com/courses/intro-to-ada/chapters/exceptions.html

由于异常不能在声明性部分中处理,因此应该将操作移动到与下面类似的包中。然后,从主过程的异常处理块中调用它。因此,您的代码在处理异常后不会终止。

with Ada.Command_line;
package Util is
--...
function Command_Argument_Count return Natural
with Pre => Ada.Command_Line.Argument_Count > 2;
--...
end Util;

--...
Exception_Handling_Block:
begin
while i <= Util.Command_Argument_Count loop
argument := to_bounded_string(
ada.command_line.argument(i)
);
ada.text_io.put_line("[" & i'image & "] "
& to_string(argument)
);
i := i + 1;
end loop;
exception
when system.assertions.assert_failure =>
ada.text_io.put_line("Failed precondition");
end Exception_Handling_Block;
--...

相关内容

最新更新