【问题标题】:Can I make OCaml produce stack traces on uncaught exceptions?我可以让 OCaml 对未捕获的异常产生堆栈跟踪吗?
【发布时间】:2014-03-04 00:52:34
【问题描述】:

在 Java 中,当异常转义 main() 函数时,堆栈跟踪会打印到控制台。你能让 OCaml 程序做同样的事情吗?

【问题讨论】:

    标签: ocaml


    【解决方案1】:

    是的,用-g编译并设置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
    

    感谢 Daniel Bünzli 指出,如果您编译为本机代码,行为可能会有所不同。这是我在我的系统上看到的(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
    

    如果你关闭内联,一切似乎都很好(至少对于这个非常简单的例子来说):

    $ 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
    

    【讨论】:

    • 应该补充一点,如果你编译成字节码,堆栈跟踪往往会更精确。
    • 你也可以使用Printexc.record_backtrace true来避免设置shell环境变量的麻烦,例如某处if !debug then Printexc.record_backtrace true; 一行;和ocamlbuild X.d.byte ocamlbuild 的目标,只是为了确定。
    • @lukstafi,这很有帮助,尤其是在使用ocamlbuild 构建项目时。
    猜你喜欢
    • 1970-01-01
    • 2010-12-20
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    相关资源
    最近更新 更多