erlang:fault/1 vs. erlang:exit/1

Richard Carlsson <>
Tue May 30 15:14:10 CEST 2006


Luke Gorrie wrote:
> Just a friendly reminder that thanks to Richard Carlsson's EUC talk we
> know that the best way to signal a crash-error is by calling
> erlang:fault(Reason) and not erlang:exit(Reason). This is because
> 'fault' will helpfully wrap the crash reason with a backtrace saying
> where it comes from whereas exit will not.

Basically, when you *really* do mean "terminate the process, giving Term
as the reason if anyone is watching this process", use exit(Term).

If you mean "a crashing error occurred", i.e., something rather unexpected
happened, which callers are not really expected to handle, then use
erlang:error(Reason), which is just a better name for erlang:fault(Reason).

If you want to throw an exception that a caller might want to catch,
then use throw(Term), and *document* that your function might throw
that exception. This lets callers program for the common case and
blissfully ignore exceptions that they are not prepared to handle.

If your function does not really have a "common case", though, you
should probably return something like {ok, Value}/{error, Reason},
but please remember that this forces all callers to do _something_
in the error case (and they must always strip the {ok, ...} part
in the success case). So design your interfaces with care.

> This makes crashes caused by 'fault' much easier to track down than
> ones caused by 'exit'. I suggest using 'fault' as your default choice.

I suggest you use the name erlang:error/1, since this matches the
exception class you will see in a try...catch. E.g.:

   try erlang:error(foo)
   catch
     error:foo -> ok
   end

but the behaviour is the same - erlang:fault/1 is just an older synonym.

As a final detail, the latest stack trace is always available through
the call erlang:get_stacktrace(), after catching an exception (regardless
of the exception type). However, when a process dies due to an exception,
the stacktrace is included in the exit term if the exception had type
'error' (or 'throw', which is converted to an 'error' when it causes
the process to terminate), but it is not included when the type is 'exit',
which is what Luke is referring to above. To summarize, there is a
difference between exceptions and the "exit terms" that are passed in
signals when processes die.

Here endeth the lesson.

	/Richard





More information about the erlang-questions mailing list