Can I make OCaml produce stack traces on uncaught exceptions?

偶尔善良 提交于 2019-12-24 04:53:05

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/21613715/can-i-make-ocaml-produce-stack-traces-on-uncaught-exceptions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!