[erlang-questions] Exceptions vs Tagged Values (was Package Support/Use)
Christian S
chsu79@REDACTED
Tue Nov 7 14:03:22 CET 2006
On 11/7/06, Samuel Rivas <samuelrivas@REDACTED> wrote:
> try file:open("foo.txt") of
> Descriptor ->
> do_something(Descriptor)
> catch
> enoent ->
> do_another_thing()
> end
> end
>
> Versus
>
> 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.
case file:open("foo.txt") of
{ok, Descriptor} ->
do_something(Descriptor);
{error, enoent} ->
do_another_thing()
end
As for external resources that we're dealing with in the example, it
is important to close the Descriptor in an 'after' section so it is
done whatever happens in the 'do_something' function.
If I am not mistaken, the after/finally/dynamic-unwind of the "try
Expr of Cases catch ... after Restore end" is just protecting the
"Expr" part and not exceptions occuring in the Cases.
If closing isnt done in 'after' then it could even be a bad idea to
handle exceptions and restarting, imagine an exception handler that
keeps opening and failing on 'do_something' a 1000 times a second,
not knowing a descriptor is leaked every time.
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.
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.
More information about the erlang-questions
mailing list