18

Suppose I have something like this :

try code_that_fails()
catch _:_ -> .....

How do I print the stacktrace in the catch block? That block catches all exceptions, but I don't know how to print the stack...

Can you help me?

ryeguy
  • 65,519
  • 58
  • 198
  • 260
Francesco
  • 299
  • 3
  • 6
  • 14
  • Francesco, if you are satisfied with one of the answers, please mark it as proper/satisfying answer – gleber Aug 27 '09 at 13:32

3 Answers3

30

From Erlang 21.0 onwards, there's a new official way to get the stack trace. An optional pattern match in the try expression on the third parameter in the exception, which will contain the stack trace:

try
   code_that_fails()
catch
   _:_:Stacktrace ->
      erlang:display(Stacktrace)
end

Older versions (OTP 20 and below)

For versions of Erlang/OTP 20 and below, you need to use get_stacktrace/0, which allows you to get the stacktrace of the last exception in the calling process:

try
   code_that_fails()
catch
   _:_ ->
      erlang:display(erlang:get_stacktrace())
end
Adam Lindberg
  • 16,447
  • 6
  • 65
  • 85
Christian
  • 9,417
  • 1
  • 39
  • 48
7

An answer for your question is:

io:format("Backtrace ~p~n", [erlang:get_stacktrace()])

The current function is at the head of the list. Read more in man 3erl erlang or erlang:get_stacktrace/0

Shunji Lin
  • 632
  • 6
  • 9
gleber
  • 4,392
  • 1
  • 26
  • 28
6

In your example, you don't need the try; you can just do

result = (catch code_that_fails()).

If an exception is raised, catch returns a tuple that contains the error code and stack trace.

Note that this is generally considered bad practice as it can mask exceptions. The stacktrace approach described in another answer is almost certainly what you want.

try is an extension of the original catch functionality; if you use it, you need to specify clauses for each exception type you would like to catch, and handle them appropriately. See sections 6.18/6.19 of the Erlang reference manual for details and clear examples.

ire_and_curses
  • 68,372
  • 23
  • 116
  • 141