Skip to content

Commit

Permalink
Clarification for try/catch documentation in the manual (#29824)
Browse files Browse the repository at this point in the history
  • Loading branch information
FreddosaurusRex authored and kshyatt committed Dec 12, 2018
1 parent 76c2593 commit 3f6eddc
Showing 1 changed file with 14 additions and 17 deletions.
31 changes: 14 additions & 17 deletions doc/src/manual/control-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -717,28 +717,25 @@ Stacktrace:

### The `try/catch` statement

The `try/catch` statement allows for `Exception`s to be tested for. For example, a customized
square root function can be written to automatically call either the real or complex square root
method on demand using `Exception`s :
The `try/catch` statement allows for `Exception`s to be tested for, and for the
graceful handling of things that may ordinarily break your application. For example,
in the below code the function for square root would normally throw an exception. By
placing a `try/catch` block around it we can mitigate that here. You may choose how
you wish to handle this exception, whether logging it, return a placeholder value or
as in the case below where we just printed out a statement. One thing to think about
when deciding how to handle unexpected situations is that using a `try/catch` block is
much slower than using conditional branching to handle those situations.
Below there are more examples of handling exceptions with a `try/catch` block:

```jldoctest
julia> f(x) = try
sqrt(x)
catch
sqrt(complex(x, 0))
julia> try
sqrt("ten")
catch e
println("You should have entered a numeric value")
end
f (generic function with 1 method)
julia> f(1)
1.0
julia> f(-1)
0.0 + 1.0im
You should have entered a numeric value
```

It is important to note that in real code computing this function, one would compare `x` to zero
instead of catching an exception. The exception is much slower than simply comparing and branching.

`try/catch` statements also allow the `Exception` to be saved in a variable. The following
contrived example calculates the square root of the second element of `x` if `x`
is indexable, otherwise assumes `x` is a real number and returns its square root:
Expand Down

0 comments on commit 3f6eddc

Please sign in to comment.