try ... after semantics
Thomas Lindgren
thomasl_erlang@REDACTED
Tue Aug 16 18:17:12 CEST 2005
What is the semantics of try ... after? In particular,
what variable bindings are available in the after
body?
Q1: My guess is, one cannot rely on any bindings made
inside the try being available? (which is why the
example below, from the erlang reference manual, 6.19,
crashes if the file:open/2 does not return {ok,...})
termize_file(Name) ->
{ok,F} = file:open(Name, [read,binary]),
try
{ok,Bin} = file:read(F, 1024*1024),
binary_to_term(Bin)
after
file:close(F)
end.
(In Java, since variables can change their values
there, I suppose one would push the file:open/2 call
into the try instead.)
Unfortunately, if we want the call to never throw an
exception, this leads to somewhat convoluted code (as
far as I can tell):
termize_file(Name) ->
try file:open(Name, [read,binary]) of
{ok, F} ->
%% original code
try ... after ... end;
Else ->
Else
end.
Q2: So, is there a better way of expressing the "safe"
termize_file using try?
Best,
Thomas
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
More information about the erlang-questions
mailing list