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 <[email protected]>
  • Loading branch information
simeonschaub and IanButterworth authored Jan 26, 2023
1 parent 335cd5e commit d775750
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 @@ -827,6 +827,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 @@ -111,7 +111,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 d775750

Please sign in to comment.