OCaml's try .. with
does not offer a finally
clause like Java. It would be useful, though, especially when dealing with side effects. For example, I like to open a file, pass the open file to a function, and close it. In case the function raises an exception I have to catch it in order to have a chance to close the file. This gets increasingly complicated when multiple files are opened and opening itself might fail as well. Is there an established programming pattern to deal with this?
Below is a simple function illustrating the problem. Function f
is applied to a channel which belongs to a file if a path
is provided and stdin
otherwise. Because there is no finally clause, close_in io
appears twice.
let process f = function
| Some path ->
let io = open_in path in
( (try f io with exn -> close_in io; raise exn)
; close_in io
)
| None -> f stdin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With