[erlang-bugs] bogus 'unsafe variable' warning with try-else

Mikael Pettersson mikpelinux@REDACTED
Thu Nov 20 13:55:36 CET 2014


Dmitry Kolesnikov writes:
 > 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

Erlang has (very) different scope rules compared to C++.

 > > On 20 Nov 2014, at 13:49, Mikael Pettersson <mikpelinux@REDACTED> 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 the file: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} = try file:read(...) after ... end".
 > > 
 > > /Mikael
 > > _______________________________________________
 > > erlang-bugs mailing list
 > > erlang-bugs@REDACTED
 > > http://erlang.org/mailman/listinfo/erlang-bugs

-- 



More information about the erlang-bugs mailing list