gpt4 book ai didi

exception - 打印堆栈跟踪

转载 作者:行者123 更新时间:2023-12-03 22:23:15 24 4
gpt4 key购买 nike

我有一个很短的测试文件:

let print_backtrace () = try raise Not_found with
Not_found -> Printexc.print_backtrace stdout;;

let f () = print_backtrace (); Printf.printf "this is to make f non-tail-recursive\n";;

f ();

我编译并运行:
% ocamlc -g test.ml      
% OCAMLRUNPARAM=b ./a.out
Raised at file "test.ml", line 1, characters 35-44
this is to make f non-tail-recursive

为什么不是 f在堆栈跟踪中列出?如何编写一个函数来打印调用它的位置的堆栈跟踪?

最佳答案

Printexc.print_backtrace 的文档说:

The backtrace lists the program locations where the most-recently raised exception was raised and where it was propagated through function calls.



它实际上似乎在做正确的事情。异常没有通过 f 传播回来。

如果我把电话转到 Printexc.print_backtrace外线调用 f ,我看到一个完整的回溯。
$ cat test2.ml
let print_backtrace () = raise Not_found

let f () = let res = print_backtrace () in res ;;

try f () with Not_found -> Printexc.print_backtrace stdout
$ /usr/local/ocaml312/bin/ocamlc -g test2.ml
$ OCAMLRUNPARAM=b a.out
Raised at file "test2.ml", line 1, characters 31-40
Called from file "test2.ml", line 3, characters 21-39
Called from file "test2.ml", line 5, characters 4-8

关于exception - 打印堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7599472/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com