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