How to get the line number of an exception in OCaml without debugging symbols?

試著忘記壹切 提交于 2020-01-01 12:36:06

问题


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")

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?


回答1:


There are global symbols __FILE__ and __LINE__ that you can use anywhere.

$ ocaml
        OCaml version 4.02.1

# __FILE__;;
- : string = "//toplevel//"
# __LINE__;;
- : int = 2
# 

Update

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"

Update 2

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)


来源:https://stackoverflow.com/questions/32127574/how-to-get-the-line-number-of-an-exception-in-ocaml-without-debugging-symbols

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