Reputation: 4956
I'm trying to catch the error in this precondition I have on the main
procedure and I'm wondering if it's possible to catch?
Do I need to move this to a different procedure and then call it in main
in order to catch it?
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;
Upvotes: 3
Views: 202
Reputation: 149
Since exception can not be handled in a declarative section, the action should be moved to a package similar to the one below. Then, call it from a exception handling block of the main procedure. So, your code will not terminate after handling the exception.
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;
--...
Upvotes: 1
Reputation: 4956
I've found my answer:
Exception handlers have an important restriction that you need to be careful about: Exceptions raised in the declarative section are not caught by the handlers of that block.
From: https://learn.adacore.com/courses/intro-to-ada/chapters/exceptions.html
Upvotes: 4