[erlang-questions] Exceptions vs Tagged Values (was Package Support/Use)
Samuel Rivas
samuelrivas@REDACTED
Tue Nov 7 15:50:35 CET 2006
Christian S wrote:
> > case file:open("foo.txt") of
> > {ok, Descriptor} ->
> > do_something(Descriptor);
> > {error, enoent} ->
> > do_another_thing();
> > {error, Reason} ->
> > {error, Reason}
> > end.
>
> Why do you have the {error, Reason} case?
>
> If you dont expect it to happen or dont have a strategy to handle it,
> you can let the case fail. The {error, Reason} will be included in the
> bad match exception if it occurs.
Because they may be other functions that would be able to handle the
exception in higher levels. And they should receive that exception,
nor a combination of badmatches, case_clauses, function_clauses, etc.
Those are errors, not exceptions.
> [snipped]
> This is why I'm often reluctant to use exceptions as indicator that
> something went one way or another. If there has been an exception then
> something happened that I had not planned/thought of when writing the
> program. I dont know what state the exceptional situation left the
> system in. With this view on exceptions, exception usage should be
> used to hang on as much information as possible on the exception data,
> so the error log makes post mortem debugging easier.
An exception is something you do not expect in the _function_ you are
writing, not in the application. If you are writing a function to open a
file you expect that this file exists. If you write a
function to check whether a file exists or not, you do not expect the
file exists, so if it does not it is not an exception.
For debug information, an exception may be handled at some application
level (e.g by a supervisor) or it may not. If it is not handled it
becomes an error (e.g. a nocatch for throws). Errors carry a trace that
is intended to provide that debugging information for crashes that _you
did not expect_.
> The original statement was that tuple tagging is bad style, not
> criticism of exceptions. Exceptions are fine and should be used when
> appropriate, but I personally dont find that exceptions are an
> argument against tuple tagged return values.
No, the argument against tagged values is that they are complicated and
astonishing return types. file:open, for example, should return a file
descriptor.
Regards
--
Samuel
More information about the erlang-questions
mailing list