Scoping rules for try - catch - finally

@Tamas_Papp :grinning: Reading discussions like this was definitely confusing (as confusing as the Julia scoping rules can be) AND helpful for me.

Loops and try-catch creating a local scope may have reasons (with try-catch-finally creating 3 separated scopes being expecially piquant). However normally you would want to pass the results to the ā€œouter worldā€.

For myself, Iā€™d sum up the following rules to avoid scoping problems:

  1. global is evil. Especially never call loop or try-catch constructs on the global (script) scope
  2. Put everything into functions as early as possible
  3. Otherwise at least put loop or try-catch into a let block
  4. Initialize the variable to be used to return results before the loop or try-catch construct. If the variable starting value is not used in the loop, initialize it with nothing

Like the following

let
    k = nothing
    for i in 1:2
        k = i
    end
    @show k
end

function f2()
    p = 0
    for j in 1:4
        p += j
    end
    return p
end

@show f2()

function tryit(sq)

    ll = mm = nothing
    try
        mm = 9
        ll = sqrt(sq)
    catch
        ll = sqrt(mm)
    finally
        ll += mm
    end
    return ll
end

@show tryit(10.0)
@show tryit("ten")
k = 2
f2() = 10
tryit(10.0) = 12.16227766016838
tryit("ten") = 12.0
3 Likes