exceptionpattern-matchingocamlmatching

Ocaml exception handling for opening input channel


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.


Solution

  • 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 -> () ;;