Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] assert caught by try with _
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2003-07-30 (17:25)
From: Didier Remy <Didier.Remy@i...>
Subject: Re: [Caml-list] unwind-protect
> One of the downsides of having people write their own unwind-protect's is
> that it's a tad tricky to get right.  The trick is ensuring that the
> cleanup code only gets run once, even if an exception is thrown in the
> middle of the cleanup.

Yes, this is essential when the finalization code is a parameter.
You do not need to use side effects, though. 

    type 'a computation = Value of 'a | Exception of exn

    let freeze_computation f x =
      try Value (f x) with z -> Exception z 

    let unfreeze_computation = function
        Value v -> v | Exception z -> raise z;;

    let try_finalize f x g y = 
      let fx = freeze_computation f x in
      let _ = g y in 
      unfreeze_computation fx

There is still a choice in the semantics regarding which exception to return
when both computations f x and g y fail. The above code reports the
exception of the finalization code. To report the exception of the
computation, replace

      let _ = g y in

      let _ = freeze_computation g y in


To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: