【问题标题】:How to assert that a function throws an exception in OCaml?如何断言函数在 OCaml 中抛出异常?
【发布时间】:2023-01-11 10:21:29
【问题描述】:

在 OCaml 中我可以捕获异常:

try some_fn () with | e -> print_endline "exception caught!"

但是反过来呢,检测一个函数没有抛出异常(当它应该抛出时)?

【问题讨论】:

    标签: exception ocaml


    【解决方案1】:

    我设法写了一些非常 hacky 的方法来实现这一点:我围绕我想要测试的函数创建了一个包装器,它在最后抛出了一些特定的异常。除了那个例外,我什么都没发现。

    exception Finished
    
    let check (fn : unit -> unit) =
      let wrapper _ = (
        fn ();
        raise Finished)
      in
      try wrapper () with e when e <> Finished -> ()
    

    在 utop 这有效:

    utop # check (fun _ -> ());;
    Exception: Finished.
    
    utop # check (fun _ -> failwith "hey");;
    - : unit = ()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-28
      • 2021-09-20
      • 2019-09-03
      • 2017-03-09
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多