Skip to content

Commit e35fbac

Browse files
myronmarstonjosevalim
authored andcommitted
Clarify semantics of after. (elixir-lang#744)
* Clarify semantics of `after`. See https://groups.google.com/forum/#!topic/elixir-lang-core/NWvFwUWo2QQ for what I was confused about. * Add clarification about file process linking.
1 parent b8bfb12 commit e35fbac

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

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

+9-1
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ It is exactly this supervision system that makes constructs like `try/catch` and
159159

160160
## After
161161

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:
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 use an `after` clause to close it--even if something goes wrong:
163163

164164
```iex
165165
iex> {:ok, file} = File.open "sample", [:utf8, :write]
@@ -172,6 +172,14 @@ iex> try do
172172
** (RuntimeError) oops, something went wrong
173173
```
174174

175+
The `after` clause will be executed regardless of whether or not the
176+
tried block succeeds. Note, however, that if a linked process exits,
177+
this process will exit and the `after` clause will not get run. Thus,
178+
`after` provides only a soft guarantee. In this case, `after` works just
179+
fine, because the opened file is also linked to the current process and
180+
will always get closed if the current process crashes, independent of the
181+
`after` clause.
182+
175183
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:
176184

177185
```iex

0 commit comments

Comments
 (0)