# Scoping rules for try - catch - finally

**URL:** <https://discourse.julialang.org/t/scoping-rules-for-try-catch-finally/32617>\
**Category:** New to Julia\
**Created:** [December 23, 2019, 10:33am UTC](https://discourse.julialang.org/t/scoping-rules-for-try-catch-finally/32617 "2019-12-23T10:33:49Z")\
**Posts on this page:** 1\
**Showing post:** 11

<div class="post-metadata">

**Author:** ![Eben60](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/eben60/32/13475_2.png) [@Eben60](https://discourse.julialang.org/u/Eben60)\
**Post date:** [January 12, 2020, 12:50pm UTC](https://discourse.julialang.org/t/scoping-rules-for-try-catch-finally/32617/11 "2020-01-12T12:50:59Z")

</div>

@Tamas_Papp 😀 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

```julia
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")

```

```julia
k = 2
f2() = 10
tryit(10.0) = 12.16227766016838
tryit("ten") = 12.0

```

---

_[View the full topic](https://discourse.julialang.org/t/scoping-rules-for-try-catch-finally/32617)._
