Re: bogus 'unsafe variable' warning with try-else

Kostis Sagonas <[email protected]>
Newsgroups gmane.comp.lang.erlang.bugs
Message-ID <[email protected]>
On 11/20/14 14:39, Dmitry Kolesnikov wrote:
> Hello,
>
> This is very valid error.
> The variable Bin is defined within code block but it is used out-side of it.
>
> I’ve never heard that any one complained about following error:
>
>     try
>     {
>        int x = 1;
>     } catch (Exception _) {
>     }
>     x++;
>
>     error: cannot find symbol

The issue has nothing to do with variables defined in blocks and used 
outside.  If it had, then the following Erlang code would also not be 
allowed, but it is:

termize_file(Name) ->
   {ok,F} = file:open(Name, [read,binary]),
   case file:read(F, 1024*1024) of
     {ok,Bin} -> ok
   end,
   binary_to_term(Bin).


I suggest you try to understand the (perhaps quite unorthodox) variable 
scoping rules of Erlang, and of try-catch in particular, and think about 
the differences between the code that was posted by Mikael (who is 
right, of course) and the Java one you posted.

Kostis


>> >On 20 Nov 2014, at 13:49, Mikael Pettersson<[email protected]>  wrote:
>> >
>> >The following, adapted from an example in the online Erlang
>> >Reference Manual, looks like a bug to me:
>> >
>>> >>cat bug.erl
>> >-module(bug).
>> >-compile(export_all).
>> >
>> >termize_file(Name) ->
>> >  {ok,F} =file:open(Name, [read,binary]),
>> >  try
>> >    {ok,Bin} =file:read(F, 1024*1024)
>> >  after
>> >    file:close(F)
>> >  end,
>> >  binary_to_term(Bin).
>>> >>erlc bug.erl
>> >bug.erl:11: variable 'Bin' unsafe in 'try' (line 6)
>> >
>> >Unless I'm missing something, there is no way to reach the
>> >binary_to_term/1 call without successfully evaluating the
>> >{ok,Bin} = ... match expression; therefore the use is not
>> >unsafe.  If thefile:read/2  call or the {ok,Bin} match fails,
>> >the after clause runs and the entire try expression fails,
>> >and the binary_to_term/1 is not reached.
>> >
>> >Reproduced with 17.3 and r15b03-1.
>> >
>> >Workaround: match on the value of the try itself:
>> >"{ok,Bin} = tryfile:read(...)  after ... end".
>> >
>> >/Mikael
>> >_______________________________________________
>> >erlang-bugs mailing list
>> >[email protected]
>> >http://erlang.org/mailman/listinfo/erlang-bugs
> _______________________________________________
> erlang-bugs mailing list
> [email protected]
> http://erlang.org/mailman/listinfo/erlang-bugs

_______________________________________________
erlang-bugs mailing list
[email protected]
http://erlang.org/mailman/listinfo/erlang-bugs
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.