Throw or return a tuple

Bjorn Gustavsson bjorn@REDACTED
Sat Aug 13 10:19:47 CEST 2005


I agree, and I think that a good rule of thumb is to use
exceptions for errors that are truly exceptional.

For instance, when opening a file, I don't find it exceptional
that a file does not exist, so I think that the file module
is right in that it returns an error tuple. Within a particular
application, file operations may in fact be exceptional, so that
it makes sense to have exception-throwing wrappers for
the file operations.

Another example, any API that would force you to catch exceptions
just to be able to successfully end a loop is WRONG. (E.g. if
the queue module would throw an execption when trying to remove an
element from an empty queue, or if end of file would cause an exception
when reading from a file.)

/Björn

"Ulf Wiger" <ulf@REDACTED> writes:

> Den 2005-08-13 06:23:05 skrev <orbitz@REDACTED>:
> 
> > 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
> (http://www.google.com/search?&q=%22let+it+crash%22+erlang)
> 
> 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
>           ...
>        end;
>     {error, Reason} ->
>        {error, Reason}
> end.
> 
> 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.
> 
> /Uffe
> -- 
> Ulf Wiger
> 

-- 
Björn Gustavsson, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list