[erlang-bugs] try..catch unsafe variable

Raimo Niskanen <>
Thu Nov 6 12:28:51 CET 2008

On Wed, Nov 05, 2008 at 08:59:06PM -0500, Matt Handler wrote:
> using R12B-2
> i've been staring at this but I can't figure out what is wrong with it:
> test() ->
>     try expression of
>         Val -> Reply = value
>     catch
>         _:_ -> Reply = exception
>     end,
>     {ok, Reply, state}.
> test2() ->
>     Reply = try expression
>             catch
>                 _:_ -> exception
>             end,
>     {ok, Reply, state}.
> test() gives a compile error: "...variable 'Reply' unsafe in 'try' (line
> ..."
> test2() does not.  can anyone clear this up for me?

You are thinking right. But when try..catch was implemented it
firstly became very messy in the compiler to export variables
from the try..end block, plus it by many is regarded as
cleaner to use the returned value making it explicit
what is used in the outer block.

Your problem gets rather messy in the general case.

    try A = a() of
        _ -> B = A
        _:_ -> B = b()
        C = B

Note that A is unsafe in the catch block
since the execution might have jumped from anywhere
in the try block. B would be valid in the 
after block and after the end if it is exported
from all try and catch clauses. And C would always
be valid after the end.

The feature to export from the after block would
be the most desirable since there is no way
today to get a value out other than sending
to yourself or storing in Ets or the process dictionary.

To complicate the matter a bit more
- the after feature is today implemented using 
nested try..catch..end blocks, so to get
export from after..end to work, some more
complicated export probably will have to work first.

Anyway, when try..end was implemented it was postponed
to tidy up these consequenses.

> _______________________________________________
> erlang-bugs mailing list
> http://www.erlang.org/mailman/listinfo/erlang-bugs


/ Raimo Niskanen, Erlang/OTP, Ericsson AB

More information about the erlang-bugs mailing list