Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions base/docs/basedocs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1063,6 +1063,20 @@ end
The syntax `catch e` (where `e` is any variable) assigns the thrown
exception object to the given variable within the `catch` block.

```julia
try
a_dangerous_operation()
catch e
if isa(e, EOFError)
@warn "The operation failed - EOF."
elseif isa(e, IOError)
@warn "The operation failed - IO Error."
else
rethrow() # ensure other exceptions can bubble up the call stack
end
end
```

The power of the `try`/`catch` construct lies in the ability to unwind a deeply
nested computation immediately to a much higher level in the stack of calling functions.

Expand Down
14 changes: 13 additions & 1 deletion doc/src/manual/control-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,8 @@ julia> sqrt_second(x) = try
sqrt(complex(x[2], 0))
elseif isa(y, BoundsError)
sqrt(x)
else
rethrow() # ensure other exceptions can bubble up the call stack
end
end
sqrt_second (generic function with 1 method)
Expand All @@ -803,8 +805,18 @@ ERROR: DomainError with -9.0:
sqrt was called with a negative real argument but will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
Stacktrace:
[...]

julia> sqrt_second([1 nothing])
ERROR: MethodError: no method matching sqrt(::Nothing)
The function `sqrt` exists, but no method is defined for this combination of argument types.
[...]
```

Use [`rethrow`](@ref) as above to continue unwinding the stack with the original exception so that
higher-level exception handlers can deal with the exception. When filtering by exception type
as above, it is often important to include `else rethrow()` so that other types of exceptions
are not hidden from the caller.

Note that the symbol following `catch` will always be interpreted as a name for the exception,
so care is needed when writing `try/catch` expressions on a single line. The following code will
*not* work to return the value of `x` in case of an error:
Expand All @@ -827,7 +839,7 @@ end
The power of the `try/catch` construct lies in the ability to unwind a deeply nested computation
immediately to a much higher level in the stack of calling functions. There are situations where
no error has occurred, but the ability to unwind the stack and pass a value to a higher level
is desirable. Julia provides the [`rethrow`](@ref), [`backtrace`](@ref), [`catch_backtrace`](@ref)
is desirable. Julia provides the [`backtrace`](@ref), [`catch_backtrace`](@ref)
and [`current_exceptions`](@ref) functions for more advanced error handling.

### `else` Clauses
Expand Down