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
exception safety / RAII ?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Gerd Stolpmann <gerd@g...>
Subject: Re: [Caml-list] exception safety / RAII ?
Am Samstag, den 05.03.2005, 13:16 -0500 schrieb Michael Benfield:
> I'm looking at OCaml coming from sort of a C++ background and I'm 
> finding it really exciting.
> There's one thing that worries me though. C++ programmers have been 
> dealing with issues of exception safety for years - it's a complicated 
> problem because coding in the presence of exceptions for all intents 
> and purposes means your function could end at any point, so how can you 
> make sure resources are deallocated? 

This is not as complicated as for C++. Memory is deallocated
automatically by the garbage collector. The remaining resources are
usually handled manually, e.g. for files

let f = open_in ... in
  ...  (* code may raise arbitrary exception *)
  any_exception ->
    close_in f;
    raise any_exception

If that happens frequently, one can also define higher-order functions
for that purpose, e.g.

let with_in_file f fn =
    let r = fn f in close_in f; r
    any_exception -> 
      close_in f; 
      raise any_exception

and then

  (open_in ...)
  (fun f -> ...)

> The C++ solution to this problem 
> is a technique called Resource Acquisition Is Initialization. C++ 
> objects have destructors, which are simply functions that will always 
> be called on exit from a scope - including if the exit is caused by an 
> exception coming up through your function. You make resource release 
> (whether the resource is memory, a socket, whatever) happen in a 
> destructor, and then you are set. This is very handy even disregarding 
> exceptions.
> So I'm just wondering what facilities OCaml has to either implement 
> this concept, or other concepts to help with exception safety? The 
> OCaml manual says: "Also, finalization can be performed by trapping all 
> exceptions, performing the finalization, then raising again the 
> exception". This makes me cringe.

Using finalization functions is often a bad idea. You cannot predict
when they are called. For example, if one tried to close files by
finalization it would be very likely to run out of file descriptors
because finalization is deferred to some unknown point in time in the

The main purpose of finalization is to synchronize O'Caml's memory
management with some foreign mechanism, e.g. because one is calling a
foreign library.

So the simplified answer to your question: There is nothing like RAII,
and one does not miss it, because O'Caml has much better concepts.

Gerd Stolpmann * Viktoriastr. 45 * 64293 Darmstadt * Germany