Skip to content

Commit 148ad02

Browse files
author
José Valim
committed
Tidy up function+try example
1 parent 5ad5b80 commit 148ad02

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

getting-started/try-catch-and-rescue.markdown

+17-16
Original file line numberDiff line numberDiff line change
@@ -157,22 +157,6 @@ Using `try/catch` is already uncommon and using it to catch exits is even more r
157157

158158
It is exactly this supervision system that makes constructs like `try/catch` and `try/rescue` so uncommon in Elixir. Instead of rescuing an error, we'd rather "fail fast" since the supervision tree will guarantee our application will go back to a known initial state after the error.
159159

160-
## Catch
161-
162-
Sometimes, you may want to wrap the entire body of a function in `try`...`catch`. Elixir offers some syntactic sugar here, letting you omit the `try` line:
163-
164-
```iex
165-
iex> defmodule CatchIt do
166-
...> def without_even_trying do
167-
...> throw "an exception"
168-
...> catch
169-
...> it -> "caught #{it}"
170-
...> end
171-
...> end
172-
iex> CatchIt.without_even_trying
173-
"caught an exception!"
174-
```
175-
176160
## After
177161

178162
Sometimes it's necessary to ensure that a resource is cleaned up after some action that could potentially raise an error. The `try/after` construct allows you to do that. For example, we can open a file and guarantee it will be closed (even if something goes wrong) with a `try/after` block:
@@ -188,6 +172,23 @@ iex> try do
188172
** (RuntimeError) oops, something went wrong
189173
```
190174

175+
Sometimes you may want to wrap the entire body of a function in a `try` construct, often to guarantee some code will be executed afterwards. In such cases, Elixir allows you to omit the `try` line:
176+
177+
```iex
178+
iex> defmodule RunAfter do
179+
...> def without_even_trying do
180+
...> raise "oops"
181+
...> after
182+
...> IO.puts "cleaning up!"
183+
...> end
184+
...> end
185+
iex> RunAfter.without_even_trying
186+
cleaning up!
187+
** (RuntimeError) oops
188+
```
189+
190+
Elixir will automatically wrap the function body in a `try` whenever one of `after`, `rescue` or `catch` is specified.
191+
191192
## Variables scope
192193

193194
It is important to bear in mind that variables defined inside `try/catch/rescue/after` blocks do not leak to the outer context. This is because the `try` block may fail and as such the variables may never be bound in the first place. In other words, this code is invalid:

0 commit comments

Comments
 (0)