[erlang-questions] Error vs. Exit
Richard Carlsson
richardc@REDACTED
Fri Aug 24 18:23:37 CEST 2007
David Mercer wrote:
> How do you decide whether to use erlang:error/1, erlang:error/2, and
> exit/1? I can’t quite grok the distinction between “when you really
> want to terminate the current process” and “something rather nasty has
> happened that callers are not really expected to handle.” Please
> advise. Thank-you.
In the exit/1 case, your code is aware that it is part of a network of
processes, and has decided that it has reached a state where it needs to
bail out and let any listening processes know about this. Preferably,
the set of such exit signals should be documented as part of the
possible behaviour of the process (e.g., as part of the documentation of
the function(s) used to spawn the process). Code further up in the call
chain should hence not catch 'exit' exceptions except in special cases
(since it changes the visible process behaviour).
A concise way of thinking about it is that exit/1 is like throw/1, but
between processes, not between function calls. (Recall that a throw is
expected to be caught somewhere before it falls out of the initial call
of the executing process - if it does not, it gets rewritten into an
error-class exception).
With exit(Term), the message sent to linked processes has the form
{'EXIT', Pid, Term}, that is, you have more precise control over the
Term part, and no messy stack trace is included. This makes it simpler
for other processes to match on the exit message.
In the error/1 case, your code does not know or care about the process
context in which it is used - it just provides some general library
functionality. By using error/1, you get a behaviour just like that
in built-in functions and operators (e.g., X/0, or 17+'true'). If this
kind of exception causes the executing process to terminate, it is not
considered normal process behaviour; the message sent to other processes
will look like {'EXIT',Pid,{Term,StackTrace}}, and furthermore the event
will be written to the error logger, which does not happen for exit/1.
/Richard
More information about the erlang-questions
mailing list