[erlang-questions] Idiomatically indicating failure in Erlang

Richard O'Keefe ok@REDACTED
Wed Jun 3 04:53:24 CEST 2009


On 3 Jun 2009, at 11:37 am, Andrew Thompson wrote:

> This reminded me that I've never been sure what the "good" way to
> indicate failure in Erlang is - do I use throw(), error()
> or what? Do I just return a tagged tuple like {error, Reason}.
>
> If I use a tagged tuple, should I avoid bloating the atom table and  
> use
> a string or should I use an atom like most of erlang's stdlib does?  
> If I
> use an atom, should I re-use one that the stdlib already uses or be  
> more
> descriptive (eg. missing_mime_boundary).
>
> If I use throw/error, should I use an new atom, an existing one or a
> more descriptive term? Should I use throw internally to get back to  
> the
> top level of my parser and then use a tagged return value?
>
> I'm just looking to get some thoughts on this since I couldn't find  
> any
> hint of a consensus on this when googling and it's always bothered me.

We just had a thread about this quite recently.

The consensus seemed to be
  - if you expect the immediate caller to know what to do about
    a failure, return tagged (or better, uniquely discriminable)
    results.  What I'm getting at here is that you have to be
    able to tell a normal return from a failure return with no
    doubt whatever, but if one is a number and the other is an
    atom, you don't need to wrap tuples around them.

  - if the caller, having matched a failure result, knows nothing
    better than to pass it along, use throw.

  - there is a distinction between ERRORS, where you may well want
    to use exit and probably have a use for some kind of full dump,
    and normal FAILURES, where you should just throw enough
    information for the catcher to be able to decide what to do about  
it.

  - dynamically creating atoms can get you into trouble, but statically
    sprinkling a few atoms around your module to distinguish between
    different outcomes isn't going to kill you.

As for parsing failures, when you want to report a failure, is it
certain that there is no alternative that could work (perhaps you
have an LL(1) grammar and the next token cannot possibly continue
a valid input), or might some ancestral parsing function want to
backtrack and try something else?  If you have a case where it is
certain that the input is invalid, you might as well throw.  Simple,
cheap, clear.


>
> Thanks,
>
> Andrew
>
> ________________________________________________________________
> erlang-questions mailing list. See http://www.erlang.org/faq.html
> erlang-questions (at) erlang.org
>
>



More information about the erlang-questions mailing list