lllllllllllll
lllllllllllll

Reputation: 9130

OCaml: define composite exception type with line number information

I am working on some OCaml code and I would like to define a composite exception type; as follows:

type exceptbase = string * string
exception UndefinedTyp of exceptbase

I would like the first element of such exception to be the line number information. However, when I use some exception handling code below, it cannot be compiled.

raise UndefinedTyp (__LOC__, "some exception messages")

So here are my questions:

  1. How to correctly define such composite exception type?
  2. Note that since the first element is always the __LOC__, is there any way I can save the effort and use __LOC__ to pre-occupy the first element?

Upvotes: 1

Views: 75

Answers (2)

camlspotter
camlspotter

Reputation: 9040

On the second point, within the vanilla OCaml, I am afraid it is impossible to omit __LOC__ argument.

But you can write a perprocessor to rewrite Undefined "some exception message" to Undefined (__LOC__, "some exception message"). Today we use PPX framework to write such a preprocessor.

BTW, OCaml's exception backtrace contains the location of raised exceptions. Setting environment variable OCAMLRUNPARAM=b, OCaml runtime prints it with source code locations when an uncaught exception terminates the program. Programatically Printexc module provides some APIs to obtain it.

Upvotes: 2

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

You just need some parentheses:

# type exceptbase = string * string
  exception UndefinedTyp of exceptbase;;
type exceptbase = string * string
exception UndefinedTyp of exceptbase
# raise (UndefinedTyp (__LOC__, "some exception message"));;
Exception:
UndefinedTyp
 ("File \"//toplevel//\", line 2, characters -13--6",
  "some exception message").

Upvotes: 1

Related Questions