打开输入通道的 Ocaml 异常处理

发布于 2024-08-24 22:19:08 字数 691 浏览 4 评论 0原文

作为 Ocaml 的初学者,我有以下当前工作代码:

...
let ch_in = open_in input_file in
try
    proc_lines ch_in
with End_of_file -> close_in ch_in;;

现在我想为不存在的输入文件添加错误处理,我写了这样:

let ch_in = try Some (open_in input_file) with _ -> None in
match ch_in with
| Some x -> try proc_lines x with End_of_file -> close_in x
| None -> () ;;

并收到错误消息:

This pattern matches values of type 'a option
but is here used to match values of type exn

对于最后一行。如果我用 None 替换 _,则会收到有关不完整匹配的错误。

我读到 exn 是异常类型。我确信我不明白这里到底发生了什么,所以请为我指出正确的方向。

As a beginner in Ocaml, I have this current working code:

...
let ch_in = open_in input_file in
try
    proc_lines ch_in
with End_of_file -> close_in ch_in;;

Now I would like to add error handling for non-existing input files, I wrote this:

let ch_in = try Some (open_in input_file) with _ -> None in
match ch_in with
| Some x -> try proc_lines x with End_of_file -> close_in x
| None -> () ;;

and get an error message:

This pattern matches values of type 'a option
but is here used to match values of type exn

For the last line. If I substitute None for _, I get an error about incomplete matching.

I read that exn is the exception type. I'm sure I don't understand what is really going on here, so please point me to the right direction.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦归所梦 2024-08-31 22:19:08

当在其他模式匹配中嵌入模式匹配时,您需要使用 ( ... )begin ... end (括号的语法糖)来封装嵌入的匹配:

let ch_in = try Some (open_in input_file) with _ -> None in
match ch_in with
| Some x -> (try proc_lines x with End_of_file -> close_in x)
| None -> () ;;

When embedding pattern matches inside other pattern matches you need to encase the embedded match with either ( ... ) or begin ... end (syntactic sugar for parentheses):

let ch_in = try Some (open_in input_file) with _ -> None in
match ch_in with
| Some x -> (try proc_lines x with End_of_file -> close_in x)
| None -> () ;;
苍暮颜 2024-08-31 22:19:08

延迟添加,但这可能更好地用处理不同异常的单个 try 来表达。

try
  let ch_in = open_in input_file in
  proc_lines ch_in
with
| Sys_error _ -> ()
| End_of_file -> close_in ch_in

Late add, but this might better be expressed with a single try that handles different exceptions.

try
  let ch_in = open_in input_file in
  proc_lines ch_in
with
| Sys_error _ -> ()
| End_of_file -> close_in ch_in
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文