Input channels: close and close_noerr

I am looking at input channel functions at OCaml library : In_channel and I do not understand the difference between close_noerr and close:

val close : t -> unit

Close the given channel. Input functions raise a Sys_error exception when they
are applied to a closed input channel, except In_channel.close, which does
nothing when applied to an already closed channel.

val close_noerr : t -> unit

Same as In_channel.close, but ignore all errors.

It says that close_noerr is the same as close “but ignore all errors”, but right above, it says that close does not raise an exception anyway ? So are the two functions identical and kept for history reasons ? What does “ignoring all errors” mean ? Does it mean that it is defined by something like

let close_noerr ic = try close ic with _ -> ()

? But since close does not raise exceptions anyway, the with part seems superfluous…

I don’t think you can read the documentation as saying that close does not raise any exception. Rather, the doc is saying that close does not raise a particular exception in a particular case.


@thomas_ridge : so you think that close may raise other exceptions ? But shouldn’t the documentation say so ? (and say which ones ?)

so you think that close may raise other exceptions ?

Like all other I/O functions, close may raise Sys_error _ to report operating system errors (as is mentioned in the comment following the definition of the Sys_error exception). The comment following the declaration of close only means that if you call close on an already-closed channel then no error is raised, but other errors may be raised if the system call fails.


1 Like

Thanks @nojb. So all I/O functions in the Stdib except:

  • close_in_noerr
  • close_out_noerr
  • flush_all
  • In_channel.close_noerr
  • Out_channel.close_noerr
  • Out_channel.flush_all

may raise Sys_error. (I searched for the string “ignore” in OCaml library : Stdlib and OCaml library : In_channel and OCaml library : Out_channel)
(This is not clearly stated in OCaml library : Stdlib). I’m sorry for the elementary nature of the question, but the documentation for OCaml seems targeted at people already knowing a lot.

1 Like

That’s right. The general rule is ocaml/stdlib.mli at 9a157026f115364635f8fe0ae5805e15ef071de0 · ocaml/ocaml · GitHub, but certain functions (which you have enumerated) have specific behaviours.


1 Like

Thanks. I had understood the paragraph you link to as “Sys_error is an exception that may be raised by some I/O functions”, whereas it means “Sys_error is an exception that may be raised by all I/O functions except [the ones I enumerated above]”. Anyway: solution accepted and thanks again!