views:

518

answers:

3

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?

+3  A: 

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
Just using `catch` is generally considered bad form. If you don't know that you want to catch *every* exception, you probably don't want it. It can make some bugs a lot harder to find.
Adam Lindberg
@Adam Lindberg: Thanks - that would explain the downvotes. I'll edit my answer.
ire_and_curses
Thanks a lot to all of you guys!! :)
Francesco
+3  A: 

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

gleber
+8  A: 

See get_stacktrace/0 which allow you to get the stacktrace of the last exception in the calling process.

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