brooks94
brooks94

Reputation: 3936

Can I make OCaml produce stack traces on uncaught exceptions?

In Java when an exception escapes the main() function, a stacktrace is printed to the console. Can you make OCaml programs do the same thing?

Upvotes: 3

Views: 410

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

Yes, compile with -g and set OCAMLRUNPARM=b

$ cat exc.ml
let f () : int =
    raise End_of_file

let g () =
    f () + 44

let _ = g()
$ ocamlc -g -o exc exc.ml
$ OCAMLRUNPARAM=b exc
Fatal error: exception End_of_file
Raised at file "exc.ml", line 2, characters 10-21
Called from file "exc.ml", line 5, characters 4-8
Called from file "exc.ml", line 7, characters 8-11

Thanks to Daniel Bünzli for pointing out that the behavior can be different if you compile to native code. Here's what I see on my system (Mac OS X 10.9.1, OCaml 4.01.0):

$ ocamlopt -g -o exc exc.ml
$ OCAMLRUNPARAM=b exc
Fatal error: exception End_of_file
Raised by primitive operation at file "exc.ml", line 5, characters 4-8
Called from file "exc.ml", line 7, characters 8-11

If you turn off inlining, things seem to work pretty well (at least for this very simple example):

$ ocamlopt -inline 0 -g -o exc exc.ml
$ OCAMLRUNPARAM=b exc
Fatal error: exception End_of_file
Raised at file "exc.ml", line 2, characters 10-21
Called from file "exc.ml", line 5, characters 4-8
Called from file "exc.ml", line 7, characters 8-11

Upvotes: 6

Related Questions