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
Raising an exception with several arguments from C
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2005-04-03 (09:47)
From: Sébastien Hinderer <Sebastien.Hinderer@e...>
Subject: Raising an exception with several arguments from C
Dear all,

In chapter 18 of Ocaml's manual, two functions are mentionned to
raise exceptions from C: caml_raise_constant which raises a
constant exception, and caml_raise_with_arg which raises an exception
with one argument.

However, assume the following declaration:

exception E of int * string;;

Then E is actually an exception with _two_ arguments, and not an
exception with one pair argument. Consequently, caml_raise_with_arg can
not be used to raise E from within a C function.

There are two solutions to this problem:

(1) declare E as follows :

exception E of (int * string)

Then E will be an exception with one argument (which is a pair), so it
will be possible to raise E thanks to caml_raise_with_arg.

(2) As can be seen in the sources of the Unix module, an exception with
n arguments (n>=2) is stored as a block of size n+1 tagged with 0. The
field 0 of this block contains the value describing the exception, as
returned by the caml_named_value function. Fields 1 to n contain values
corresponding to arguments 1 to n of E (this encoding comes from the
fact that exceptions are variants, I guess?).

Once this block (let's call it res) is allocated and properlz filled,
E can be raised thanks to a call such as
(caml_raise is declared in caml/fail.h).

Unfortunately, caml_raise does not seem to be documented in Caml's
manual. Moreover, as far as I know, nothing is said about raising
exceptions with more than one argument.
Perhaps this point could be clarified in future versions of the manual ?