如何在不调试符号的情况下获取OCaml中的异常的行号? [英] How to get the line number of an exception in OCaml without debugging symbols?
问题描述
有没有一种无需调试符号即可获取OCaml中异常行号的好方法吗?当然,如果打开调试符号并使用OCAMLRUNPARAM=b
运行,则可以获取回溯信息.但是,我实际上并不需要整个回溯,因此我想一个无需调试符号的解决方案.目前,我们可以编写类似
Is there a good way to get the line number of exception in OCaml without debugging symbols? Certainly, if we turn on debugging symbols and run with OCAMLRUNPARAM=b
, we can get the backtrace. However, I don't really need the whole backtrace and I'd like a solution without debugging symbols. At the moment, we can write code like
try
assert false
with x ->
failwith (Printexc.to_string x ^ "\nMore useful message")
以便从assert中获取文件和行号,但这似乎很尴尬.有没有更好的方法来获取异常的文件和行号?
in order to get the file and line number from assert, but this seems awkward. Is there a better way to get the file and line number of the exception?
推荐答案
在任何地方都可以使用全局符号__FILE__
和__LINE__
.
There are global symbols __FILE__
and __LINE__
that you can use anywhere.
$ ocaml
OCaml version 4.02.1
# __FILE__;;
- : string = "//toplevel//"
# __LINE__;;
- : int = 2
#
更新
正如@MartinJambon所指出的,还有__LOC__
,它在一个字符串中给出了文件名,行号和字符位置:
As @MartinJambon points out, there is also __LOC__
, which gives the filename, line number, and character location in one string:
# __LOC__;;
- : string = "File \"//toplevel//\", line 2, characters -9--2"
更新2
这些符号在 Pervasives模块中定义.完整列表为:__LOC__
,__FILE__
,__LINE__
,__MODULE__
,__POS__
,__LOC_OF__
,__LINE_OF__
,__POS_OF__
.
These symbols are defined in the Pervasives module. The full list is: __LOC__
, __FILE__
, __LINE__
, __MODULE__
, __POS__
, __LOC_OF__
, __LINE_OF__
, __POS_OF__
.
最后三个返回有关整个表达式而不是文件中单个位置的信息:
The last three return information about a whole expression rather than just a single location in a file:
# __LOC_OF__ (8 * 4);;
- : string * int = ("File \"//toplevel//\", line 2, characters 2-9", 32)
这篇关于如何在不调试符号的情况下获取OCaml中的异常的行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!