Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emulating try-with-finally in OCaml

Tags:

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