Ocaml 尝试解决问题

问题描述 投票:0回答:1

我不明白 try ... with ... Ocaml 功能的行为。

这里有一个小样本来重现我的问题:

let () =
  try int_of_string "4" with
  | Failure -> -1
  | n -> n

我用

编译

ocamlc 测试.ml

然后我收到此错误:

文件“test.ml”,第 2 行,字符 6-23:
2 | 尝试 int_of_string "4" 与

错误:此表达式的类型为 int,但表达式应为 unit 类型

如何修改我的小代码示例以使其正常工作?

try-catch ocaml
1个回答
0
投票

您的代码可以解读为

let () = (* I expect an unit result *)
 try int_of_string "4"
    (* if the call to `int_of_string` succeeds returns this result,
       which is an int *)
 with (* otherwise if an exception was raised* *)
 | Failure ->
   (* returns 1 if the raised exception was the `Failure` exception *)
   -1 
 | n -> n (* otherwise returns the exception `n` *)

由于有很多小剪纸而失败。修正后的版本是

let n =
  try int_of_string "4" with 
  | Failure _  (* Failure contains a error message as an argument *)  -> - 1

尽管如此,我建议使用

match ... with exception ... -> ...
结构,它可能更接近你的直觉

let n = match int_of_string "4" with
| exception Failure _msg -> -1
| x -> x (* if there was no exception, returns the result *)

但你也可以通过

避免异常
let n = match int_of_string_opt "4" with
| None -> -1
| Some x -> x

甚至

let n = Option.value ~default:(-1) (int_of_string_opt "4")
© www.soinside.com 2019 - 2024. All rights reserved.