Skip to content

Commit d15368a

Browse files
committed
try-catch-and-rescue "Variables scope": offer alternative
1 parent ff92803 commit d15368a

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

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

+20-7
Original file line numberDiff line numberDiff line change
@@ -166,14 +166,27 @@ It is important to bear in mind that variables defined inside `try/catch/rescue/
166166

167167
```iex
168168
iex> try do
169-
...> from_try = true
170-
...> after
171-
...> from_after = true
169+
...> raise "fail"
170+
...> what_happened = :did_not_raise
171+
...> rescue
172+
...> _ -> what_happened = :rescued
172173
...> end
173-
iex> from_try
174-
** (RuntimeError) undefined function: from_try/0
175-
iex> from_after
176-
** (RuntimeError) undefined function: from_after/0
174+
iex> what_happened
175+
** (RuntimeError) undefined function: what_happened/0
176+
```
177+
178+
Instead, you can store the value of the `try` expression:
179+
180+
```iex
181+
iex> what_happened =
182+
...> try do
183+
...> raise "fail"
184+
...> :did_not_raise
185+
...> rescue
186+
...> _ -> :rescued
187+
...> end
188+
iex> what_happened
189+
:rescued
177190
```
178191

179192
This finishes our introduction to `try`, `catch` and `rescue`. You will find they are used less frequently in Elixir than in other languages although they may be handy in some situations where a library or some particular code is not playing "by the rules".

0 commit comments

Comments
 (0)