Skip to content

Commit

Permalink
add docs for try-catch-else (#48414)
Browse files Browse the repository at this point in the history
ref #46928

Co-authored-by: Ian Butterworth <i.r.butterworth@gmail.com>
(cherry picked from commit d775750)
  • Loading branch information
simeonschaub authored and KristofferC committed Feb 6, 2023
1 parent bcb5bc9 commit f66f52c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
38 changes: 38 additions & 0 deletions doc/src/manual/control-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -819,6 +819,44 @@ no error has occurred, but the ability to unwind the stack and pass a value to a
is desirable. Julia provides the [`rethrow`](@ref), [`backtrace`](@ref), [`catch_backtrace`](@ref)
and [`current_exceptions`](@ref) functions for more advanced error handling.

### `else` Clauses

!!! compat "Julia 1.8"
This functionality requires at least Julia 1.8.

In some cases, one may not only want to appropriately handle the error case, but also want to run
some code only if the `try` block succeeds. For this, an `else` clause can be specified after the
`catch` block that is run whenever no error was thrown previously. The advantage over including
this code in the `try` block instead is that any further errors don't get silently caught by the
`catch` clause.

```julia
local x
try
x = read("file", String)
catch
# handle read errors
else
# do something with x
end
```

!!! note
The `try`, `catch`, `else`, and `finally` clauses each introduce their own scope blocks, so if
a variable is only defined in the `try` block, it can not be accessed by the `else` or `finally`
clause:
```jldoctest
julia> try
foo = 1
catch
else
foo
end
ERROR: UndefVarError: `foo` not defined
```
Use the [`local` keyword](@ref local-scope) outside the `try` block to make the variable
accessible from anywhere within the outer scope.

### `finally` Clauses

In code that performs state changes or uses resources like files, there is typically clean-up
Expand Down
2 changes: 1 addition & 1 deletion doc/src/manual/variables-and-scoping.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ x = 1

Note that the interactive prompt (aka REPL) is in the global scope of the module `Main`.

## Local Scope
## [Local Scope](@id local-scope)

A new local scope is introduced by most code blocks (see above [table](@ref
man-scope-table) for a complete list). If such a block is syntactically nested
Expand Down

0 comments on commit f66f52c

Please sign in to comment.