【问题标题】:Custom condition failure messages in Ada 2012Ada 2012 中的自定义条件失败消息
【发布时间】:2020-07-03 19:26:43
【问题描述】:

有没有办法为前置条件和后置条件指定自定义错误/失败消息,类似于谓词的Predicate_Failure?我似乎无法在官方文档中找到任何内容。 TIA。

【问题讨论】:

    标签: ada predicate design-by-contract preconditions post-conditions


    【解决方案1】:

    您可以使用 raise 表达式(参见例如 here),如下例所示。

    ma​​in.adb

    pragma Assertion_Policy (Check);
    
    with Ada.Text_IO;
    with Ada.Float_Text_IO;
    
    procedure Main is
       
       package TIO renames Ada.Text_IO;
       package FIO renames Ada.Float_Text_IO;
       
       
       function Reciprocal (X : Float) return Float is (1.0 / X)
         with Pre => (X /= 0.0 or else
                        raise Constraint_Error with "X must not be 0.");
       
    begin
       FIO.Put (Reciprocal (2.0));
       TIO.New_Line;
       
       FIO.Put (Reciprocal (0.0));
       TIO.New_Line;   
    end Main;
    

    输出

    $ ./obj/main
     5.00000E-01
    
    raised CONSTRAINT_ERROR : X must not be 0.
    [2020-07-03 22:20:25] process exited with status 1, elapsed time: 00.32s
    

    【讨论】:

    • 太好了,谢谢!不知何故错过了这里的明显之处。
    • 不客气。我稍微更新了示例:您也可以使用or else 代替if 表达式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 2014-10-19
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多