For out of bounds array accesses OCaml throws an exception like this one:
# [|1;2;3|].(12);;
Exception: Invalid_argument "index out of bounds".
Ok on the toplevel—but in compiled code an exception like that isn't very helpful!
Instead I would prefer something more verbose, something like:
Failure("Array.get: index out of bounds (File \"MI_Pl.ml\", line 10388, characters 80-87)")
To get exceptions like this, I use a combination of cppo
and this macro:
#define ARRAY_GET(__arr__,__ix__) \
(let __tx__ = (__ix__) in \
if __tx__ >= 0 && __tx__ < Array.length (__arr__) \
then Array.unsafe_get (__arr__) __tx__ \
else failwith (Printf.sprintf "Array.get: index out of bounds (%s)" __LOC__))
This kind of works, but it also quite ugly...
Is there a better way to this?