打开输入通道的 Ocaml 异常处理
作为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当在其他模式匹配中嵌入模式匹配时,您需要使用
( ... )
或begin ... end
(括号的语法糖)来封装嵌入的匹配:When embedding pattern matches inside other pattern matches you need to encase the embedded match with either
( ... )
orbegin ... end
(syntactic sugar for parentheses):延迟添加,但这可能更好地用处理不同异常的单个
try
来表达。Late add, but this might better be expressed with a single
try
that handles different exceptions.