diff --git a/base/docs/basedocs.jl b/base/docs/basedocs.jl index 08c8aa0fb2357..f9441b5be4368 100644 --- a/base/docs/basedocs.jl +++ b/base/docs/basedocs.jl @@ -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. diff --git a/doc/src/manual/control-flow.md b/doc/src/manual/control-flow.md index 231ec53741111..04bb1ea621f33 100644 --- a/doc/src/manual/control-flow.md +++ b/doc/src/manual/control-flow.md @@ -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) @@ -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: @@ -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