Ocaml exception handling for open input channel

As a newbie to 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 nonexistent 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 you get an error: this pattern matches values ​​of type 'a option but is used here to match values ​​of type exn for the last line. If I replace None with _, I get an error about incomplete matching.

I read that exn is an exception type. I’m sure I don’t understand what is happening here, so please point me in the right direction. Thank!

+3
source share
1 answer

( ... ) 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 -> () ;;
+6

Source: https://habr.com/ru/post/1735790/


All Articles