在Python中,用单元测试来管理某些错误是很简单的。例如,为了验证一个列表是否被清空,我可以使用 assert test != []
假设空 list let test = [];;
try
ignore (nth test 0)
with
Not_found -> print_string("Erreur!");;
Exception: Failure "nth"
我需要提出一个错误 - print_string ("Erreur!")
碰上 Exception: Failure "nth"
. 到目前为止 try/with
并没有真正帮助我。在Ocaml中,是否有一种工作方法可以在我得到 Exception: Failure "nth"
?
在Python中,通过单元测试来管理某些错误是非常简单的。例如,为了验证一个列表是否被清空,我可以使用
assert test != []
你可以在OCaml中做完全相同的事情(modulo语法)
let require_non_empty xs =
assert (xs <> [])
如果你想嘘一个异常,并在它不存在的情况下提出,你可以使用匹配结构,下面是你的例子在OCaml中如何表达。
let require_empty xs = match List.nth xs 0 with
| exception _ -> ()
| _ -> failwith "the list shall be empty"
此外,测试框架,如。OUnit2,提供特殊功能,如 assert_raises
对于这些特定的情况。
你似乎在问,你是否可以测试特定的例外情况。是的,可以。异常处理部分在 with
是一个类似于 match
的表达式。
try
ignore (List.nth [] 0)
with
| Not_found -> ()
| Failure s -> print_string ("Erreur: " ^ s)
| _ -> ()
(依赖作为参数提供给 Failure
. 事实上,编译器警告你不要这样做)。)
OCaml也有一个 asssert
表达式。
# let list = [] in assert (List.length list > 0);;
Exception: Assert_failure ("//toplevel//", 1, 17).
你可以用 try/with
来处理所产生的异常,当然。的参数。Assert_failure
给出文件名、行号和行上的字符号。