[erlang-questions] Variable 'Error' unsafe in 'try'

Jayson Vantuyl kagato@REDACTED
Fri Oct 2 10:40:00 CEST 2009


The previous example (from the mailing list last year) doesn't exactly  
apply.  In that case, test1 and test2 are different functions, so  
there's no danger of Error being bound in the second function.  In  
that particular case, it has to do with the fact that a binding in an  
after clause isn't handled in a way that the compiler thinks is safe  
(even though it should be).

In your case, since they are in the same function, the second Error is  
already potentially bound to the result of the first try and the  
second usage considers the use of Error in the catch clause to already  
be bound.  Since the first try has an exit path that doesn't bind  
Error (namely, the successful path), it's unsafe use of the binding  
anyways.

This works:

> test() ->
>    try ok catch
>        _:Error0 -> Error0
>    end,
>    try ok catch
>        _:Error1 -> Error1
>    end.

Within a function in Erlang, a binding NEVER goes "out-of-scope" or  
are in any way "unbound".  Well, that's not entirely true, there are  
three times that I know of:

1.  Variables defined in a fun() inside of a function go out of  
(lexical) scope at the end of the fun().
2.  Variables can be shadowed in a nested function head (effectively  
unbinding the parent variable).
3.  Variables can be shadowed by bindings inside of a generator.

Consider the following:

> test(X) ->
>   fun(X) ->
>     [X || X <- X]
>   end.

Mind you, this is unnatural code-that-should-not-be.

On Oct 2, 2009, at 12:30 AM, Adam Lindberg wrote:

> Hi!
>
> I'm working with some try-catch exceptions and have stumbled upon  
> something which I think is a bit wierd. There was an explanation a  
> year ago on the mailing list which explained why variables bound  
> inside the try-catch expression were not safe to use when an  
> exception got caught (http://erlang.org/pipermail/erlang-bugs/2008-November/001083.html 
> ). This is fully understandable.
>
> I've compacted my case to this minimal one:
>
> test() ->
>    try ok catch
>        _:Error -> Error
>    end,
>    try ok catch
>        _:Error -> Error
>    end.
>
> I get an error saying that the variable 'Error' is unsafe in the  
> first line of the function (the first try-catch statement). With  
> just one try-catch statement it works fine.
>
> Why is this? I was under the impression that stuff inside try-catch  
> statements were block local, but that isn't the case? I can't access  
> Error outside the try-catch statement so it shouldn't be a problem,  
> should it?
>
> Cheers,
> Adam
>
> ________________________________________________________________
> erlang-questions mailing list. See http://www.erlang.org/faq.html
> erlang-questions (at) erlang.org
>



-- 
Jayson Vantuyl
kagato@REDACTED







More information about the erlang-questions mailing list