How to get exception line number in OCaml without debugging characters?

Is there a good way to get the exception line number in OCaml without debugging characters? Of course, if we turn on debugging characters and run using OCAMLRUNPARAM=b , we can get the backtrace. However, I don't need all the backtracking, and I need a solution without debugging characters. At the moment, we can write code like

 try assert false with x -> failwith (Printexc.to_string x ^ "\nMore useful message") 

to get the file and line number from assert, but this seems inconvenient. Is there a better way to get the file number and exception numbers?

+4
source share
1 answer

There are global characters __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 file name, line number and character location on the same line:

 # __LOC__;; - : string = "File \"//toplevel//\", line 2, characters -9--2" 

Update 2

These characters are defined in the Pervasives module . Full list: __LOC__ , __FILE__ , __LINE__ , __MODULE__ , __POS__ , __LOC_OF__ , __LINE_OF__ , __POS_OF__ .

The last three return information about the entire expression, and not just in one place in the file:

 # __LOC_OF__ (8 * 4);; - : string * int = ("File \"//toplevel//\", line 2, characters 2-9", 32) 
+7
source

All Articles