处理异常:失败 "nth"

Handle Exception: Failure "nth"

在Python中,使用单元测试来管理某些错误非常简单。例如,要验证列表是否为空,我可以使用 assert test != []

假设空list let test = [];;

try
 ignore (nth test 0)
with
 Not_found -> print_string("Erreur!");;
   Exception: Failure "nth"

遇到Exception: Failure "nth"时需要报错-print_string ("Erreur!")。到目前为止 try/with 并没有真正帮助我。在 Ocaml 中,是否有一种解决方法可以在我得到 Exception: Failure "nth"?

时引发错误并打印一些内容

您似乎在问是否可以测试特定的异常。是的。 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 的参数给出文件名、行号和行中的字符号。

In Python, it is quite simple to manage certain error, with unit tests. For instance, to verify if a list is emptied or not, I can use assert test != []

您可以在 OCaml 中执行完全相同的操作(模语法)

let require_non_empty xs = 
  assert (xs <> [])

如果你想隐藏一个异常并在它不存在时引发,你可以使用 match 结构,这里是你的例子如何用 OCaml 表达,

let require_empty xs = match List.nth xs 0 with
  | exception _ -> ()
  | _ -> failwith "the list shall be empty"

此外,测试框架(例如 OUnit2)为这些特定情况提供了特殊功能,例如 assert_raises