该代码片段使用 My_Color'Value 从 String 转换为 My_Color ,它只是引发 Constraint_Error 或 Data_Error ,正如预期的那样。如果您输入正确的颜色,第一块代码就可以工作,但是如果输入错误的颜色或随机字符,则会引发 Constraint_Error 。
with Ada.Text_IO;
procedure test_get_enum_loop is
type My_Color is (red, yellow, green);
package Color_IO is new Ada.Text_IO.Enumeration_IO (My_Color);
use Color_IO;
use Ada.Text_IO;
Color : My_Color;
begin
-- Loop with 'value attribute
loop
begin
Put ("Enter a color: ");
Color := My_Color'Value(Get_Line);
Put_Line ("The color is " & Color'Image);
exit;
exception
when Data_Error =>
Put_Line ("Error, you did not enter a Color");
when Constraint_Error =>
Put_Line ("Error, Constraint_Error");
end;
end loop;
此代码是上述代码的延续,并且按预期工作:
New_Line;
-- Loop with Get
loop
declare
Color : My_Color;
Last : Natural;
begin
Put ("Enter a color: ");
Get (Get_Line, Color, Last);
Put_Line ("The color is " & Color'Image);
exit;
exception
when Data_Error =>
Put_Line ("Error, you did not enter a Color");
when Constraint_Error =>
Put_Line ("Error, Constraint_Error");
when End_Error =>
Put_Line ("You entered Nothing, try again");
end;
end loop;
end test_get_enum_loop;
来自好奇自闭症患者的问候
原因是Data_Error是*_IO包独有的异常,所以像Get这样的函数会抛出Data_Error。像 'Value 这样的核心语言属性不是 IO 包的一部分,因此它们无法直接访问 Data_Error 异常。相反,他们使用核心标准异常之一,Constraint_Error。在 Standard 包中找到的标准例外列表是:
Constraint_Error: exception;
Program_Error : exception;
Storage_Error : exception;
Tasking_Error : exception;