[erlang-questions] When to return {ok, Value} or just the Value

Garrett Smith g@REDACTED
Wed Nov 16 17:25:32 CET 2011


On Wed, Nov 16, 2011 at 3:04 AM, Joe Armstrong <erlang@REDACTED> wrote:
>
> On Wed, Nov 16, 2011 at 1:38 AM, Richard Carlsson
> <carlsson.richard@REDACTED> wrote:
>
>> Using error(X), on the other hand, says that you just want to signal an
>> error but with no particular intent of ending the process; it is not
>> possible to proceed, but the caller might want to catch the exception and
>> try something else. Your code has no opinion on what to do on a process
>> level. An uncaught error (or throw) will terminate the process and also
>> bring down any non-error-trapping linked processes, and the error logger
>> will log the crash as an anomalous process termination.
>
> I have a problem with this - when you write library routines, or just write
> a function I'm not normally thinking about the process(s) in which the
> function is called.

This was my reaction as well. But on casual glance at the Erlang/OTP
source, it does seem to generally hold: exit is used by functions that
are aware of a process context and intend to exit that process; error
is used to communicate "I can't do that".

Mechanically, error exceptions provide a stack trace, exits do not:

Eshell V5.8.5  (abort with ^G)
1> catch(exit(foo)).
{'EXIT',foo}
2> catch(error(foo)).
{'EXIT',{foo,[{erl_eval,do_apply,5},
              {erl_eval,expr,5},
              {shell,exprs,7},
              {shell,eval_exprs,7},
              {shell,eval_loop,3}]}}

If you're just punting on an operation that you can't or don't want to
perform, error seems to be the convention:

3> dict:fetch(dict:new(), "foo").
** exception error: {badrecord,dict}
     in function  dict:get_slot/2
     in call from dict:fetch/2
4> 1 / 0.
** exception error: bad argument in an arithmetic expression
     in operator  '/'/2
        called as 1 / 0

Garrett



More information about the erlang-questions mailing list