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

Richard Carlsson carlsson.richard@REDACTED
Tue Nov 15 22:36:09 CET 2011

On 2011-11-15 18:35, Fred Hebert wrote:
>  1. I tend to use exit/1 when my semantics are 'this process is done
>     running, nothing more to do here'.
>  2. I use 'error/1' when the semantics are 'there is likely an error in
>     code that will require some programmer to change what they do'.
>  3. 'throw/1' is usually something I use in a module-local manner for
>     non-local returns for exceptions I expect to handle in-module.
>  4. I use {error, Something} when I need to express some
>     exceptional-but-not-deadly case to the user, something they might
>     know how to handle and fix, or a boundary condition that they might
>     expect. It's not deadly or game changing, but it's not a normal
>     result either,
> That's the general way I picked after researching exceptions and their
> meaning when writing Learn You Some Erlang. Different people who worked
> on Erlang seem to disagree on the semantics of throw vs. error (although
> they seemed to agree on exits), so it's just not exactly simple.

Yes, this is the way the different exception classes should be used:

   * 'exit' for when the process ought to terminate and propagate the 
signal to anyone who's linked to it.

   * 'error' for run-time errors (no matter whether it's compiler 
generated as when no function clause can match or whether it's because 
your complicated assertion fails, it should be an error).

   * 'throw' for nonlocal returns and for the kind of interface where 
you'd like to return a plain value in the normal case but where there 
are some predictable failure cases like throw({not_found, File}) that 
may happen occasionally and that you want to document so that an 
interested user can catch them while uninterested users can simply 
program for the success case.

Note that if you are looking at older code (or code written by certain 
oldtimers), it tends to use only exit(X), because in the old days 
error(X) didn't exist and there wasn't much consensus about what to use 
throw(X) for. But today, exit(X) should be used only to show intent to 
terminate the process and communicate information to linked processes. 
It can of course be caught, but someone catching it should be aware that 
he's now blocking this intent. Don't habitually catch every possible 
exception in the protected sections - if you don't know what to do with 
a particular exception, you should let it fall through.


More information about the erlang-questions mailing list