1

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?

repeat
  • 18,496
  • 4
  • 54
  • 166

1 Answers1

3

You can compile with -g and when running the code ask for traceback with OCAMLRUNPARAM=b

$ cat m.ml
let a = Array.make 12 0

let f n = a.(n)

let main () =
    Printf.printf "%d\n" (f 12)

let () = main ()
$ ocamlopt -g -o m m.ml
$ OCAMLRUNPARAM=b ./m
Fatal error: exception Invalid_argument("index out of bounds")
Raised by primitive operation at M.f in file "m.ml" (inlined), line 3, characters 10-15
Raised by primitive operation at M.main in file "m.ml", line 6, characters 25-31
Called from M in file "m.ml", line 8, characters 9-16
Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108