【发布时间】:2023-01-11 10:21:29
【问题描述】:
在 OCaml 中我可以捕获异常:
try some_fn () with | e -> print_endline "exception caught!"
但是反过来呢,检测一个函数没有抛出异常(当它应该抛出时)?
【问题讨论】:
在 OCaml 中我可以捕获异常:
try some_fn () with | e -> print_endline "exception caught!"
但是反过来呢,检测一个函数没有抛出异常(当它应该抛出时)?
【问题讨论】:
我设法写了一些非常 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 = ()
【讨论】: