You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: getting-started/try-catch-and-rescue.markdown
+17-16
Original file line number
Diff line number
Diff line change
@@ -157,22 +157,6 @@ Using `try/catch` is already uncommon and using it to catch exits is even more r
157
157
158
158
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.
159
159
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
-
176
160
## After
177
161
178
162
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
188
172
** (RuntimeError) oops, something went wrong
189
173
```
190
174
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
+
191
192
## Variables scope
192
193
193
194
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