Question

I have a block of code as follows:

try
   raise Exit (* body *)
with
| e ->
  Printexc.record_backtrace true;
  printf "Unexpected exception : %s\n" (Printexc.to_string e);
  let x = Printexc.get_backtrace () in
  print_string x;
  Printexc.print_backtrace stdout

The code in body does raise an exception, and it shows Unexpected exception : Pervasives.Exit, However it doesn't print any backtrace.

I compile the file with -g and export OCAMLRUNPARAM=b, does anyone know the reason why the backtrace cannot be printed?

Was it helpful?

Solution

I don't see many functions in your code, so most likely there's no stack trace to print. See the previous answer here: Printing stack traces

It strikes me today that a likely problem is that OCAMLRUNPARAM isn't actually set in your process. It can be tricky to get environment variables to pass down through make(1) commands. One reason is that each line in a Makefile is executed by a different shell.

Another thing that affects backtraces is inlining. If your functions are complex this probably isn't affecting you. But you can turn off almost all inlining with -inline 0. It's unlikely that this would make the difference between no stack trace and stack trace. It might make a difference between shorter and longer stack traces.

Here is an experiment where inlining makes a difference:

$ cat m.ml
try
    let f () : int = raise Exit
    in let g () = f () + 2
    in let h () = g () + 3
    in let main () = Printf.printf "%d\n" (h () + 4)
    in main ()
with
    e -> Printf.printf "%s" (Printexc.get_backtrace ())
$ ocamlopt -inline 10 -g -o m m.ml
$ OCAMLRUNPARAM=b m
Raised by primitive operation at file "m.ml", line 3, characters 18-22
$ ocamlopt -inline 0 -g -o m m.ml
$ OCAMLRUNPARAM=b m
Raised at file "m.ml", line 2, characters 27-31
Called from file "m.ml", line 3, characters 18-22
Called from file "m.ml", line 4, characters 18-22
Called from file "m.ml", line 5, characters 43-47
Called from file "m.ml", line 6, characters 7-14
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top