Throw or return a tuple

Ulf Wiger <>
Sat Aug 13 09:25:50 CEST 2005

Den 2005-08-13 06:23:05 skrev <>:

> I find myself often confused about which to do, should I throw an  
> exception when an error happens in a function or always go with  
> returning {ok, Value} or {error, Whatever}.

This has been discussed now and then on the list.
I think the cleanest way to program is to have functions
that either return a good value or throw an exception
(amendments to the rule will follow).

Traditionally, there have been some problems with
debugging this style of programming, but the problems
are being addressed, e.g. with the new 'try' construct.

Coupled with this is the 'let it crash' philosophy

A place where it's appropriate to wrap return values is
for example:

dict:read(Key) -> Value | exit()
dict:search(Key) -> {found, Value} | not_found

> Some people seem try to tell me that I should use {error, Value} and  
> "get out of your OO mindset with exceptions".  But I think that is bull.

I agree.

One problem with always wrapping return values is that
you get a lot of code like this:

case foo(...) of
    {ok, Result} ->
       case bar(...) of
    {error, Reason} ->
       {error, Reason}

That is, the most common situation is that you can't
handle the error return value where it first occurs,
and just pass it on to the caller. Throwing exceptions
is a much better way to accomplish this.

Ulf Wiger

More information about the erlang-questions mailing list