You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ada代码中'Value属性为何抛出Constraint_Error而非Data_Error?

Ada枚举类型字符串转换异常问题解析

在Ada代码中,使用My_Color'Value将字符串转换为自定义枚举类型My_Color时,输入错误颜色或随机字符会触发Constraint_Error,而非预期的Data_Error;输入正确颜色时代码可正常运行。

问题代码示例

以下代码使用'Value属性进行枚举类型转换,错误输入会触发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; 
end test_get_enum_loop;

预期行为的实现(使用Get方法)

使用Enumeration_IO提供的Get方法时,代码可按预期触发对应异常:

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;

自定义验证实现预期效果

通过添加输入验证逻辑,可实现输入错误或空值时抛出对应异常的预期效果:

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: ");
         declare
            Tmp : String := Get_Line;
         begin
            if Tmp = "" then
               raise End_Error;
            else   
               Color := My_Color'Value(Tmp);
            end if;
         end;    
         Put_Line ("The color is " & Color'Image);
         exit;
      exception
         when End_Error =>
            New_Line;
            Put_Line ("Error, you entered nothing, try again");
            New_Line;
         when Constraint_Error =>
            New_Line;
            Put_Line ("Error, you did not enter a Color, try again");
            New_Line;
      end;     
   end loop; 
end test_get_enum_loop;

来自curiousautistic的问候

内容的提问来源于stack exchange,提问作者curiousautistic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 10:13:13