Is there a predefined programming pattern to handle this?
Yes, wrapper functions that separate resource cleanup from exception handling. I use a common shell unwind(LISPism, which I rather use):
let unwind ~(protect:'a -> unit) f x =
try let y = f x in protect x; y
with e -> protect x; raise e
, , protect; , , protect , , Yaron Minski's, , :
let unwind ~protect f x =
let module E = struct type 'a t = Left of 'a | Right of exn end in
let res = try E.Left (f x) with e -> E.Right e in
let () = protect x in
match res with
| E.Left y -> y
| E.Right e -> raise e
, :
let with_input_channel inch f =
unwind ~protect:close_in f inch
let with_output_channel otch f =
unwind ~protect:close_out f otch
let with_input_file fname =
with_input_channel (open_in fname)
let with_output_file fname =
with_output_channel (open_out fname)
, with_, , ; , à la Haskell, :
let () = with_output_file "foo.txt" $ fun otch ->
output_string otch "hello, world";
(* ... *)
. :
let with_open_graph spec (proc : int -> int -> unit) =
unwind ~protect:Graphics.close_graph (fun () ->
proc (Graphics.size_x ()) (Graphics.size_y ());
ignore (Graphics.wait_next_event [Graphics.Button_down]);
ignore (Graphics.wait_next_event [Graphics.Button_up]))
(Graphics.open_graph spec)
with_open_graph " 400x300" $ fun width height -> (*...*).
user593999