Skip to content

Commit 44c81ae

Browse files
author
José Valim
committed
Document how ErlangError works, closes #2166
1 parent c6c6a27 commit 44c81ae

File tree

1 file changed

+40
-11
lines changed

1 file changed

+40
-11
lines changed

lib/elixir/lib/kernel/special_forms.ex

Lines changed: 40 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1377,7 +1377,7 @@ defmodule Kernel.SpecialForms do
13771377
"""
13781378
defmacro case(condition, blocks)
13791379

1380-
@doc """
1380+
@doc ~S"""
13811381
Evaluate the given expressions and handle any error, exit
13821382
or throw that may have happened.
13831383
@@ -1390,10 +1390,10 @@ defmodule Kernel.SpecialForms do
13901390
IO.puts "Invalid argument given"
13911391
catch
13921392
value ->
1393-
IO.puts "caught \#{value}"
1393+
IO.puts "caught #{value}"
13941394
else
13951395
value ->
1396-
IO.puts "Success! The result was \#{value}"
1396+
IO.puts "Success! The result was #{value}"
13971397
after
13981398
IO.puts "This is printed regardless if it failed or succeed"
13991399
end
@@ -1439,10 +1439,39 @@ defmodule Kernel.SpecialForms do
14391439
x -> nil
14401440
end
14411441
1442-
## Catching exits and Erlang errors
1442+
## Erlang errors
1443+
1444+
Erlang errors are transformed into Elixir ones during rescue:
1445+
1446+
try do
1447+
:erlang.error(:badarg)
1448+
rescue
1449+
ArgumentError -> :ok
1450+
end
1451+
1452+
The most common Erlang errors will be transformed into their
1453+
Elixir counter-part. Those which are not will be transformed
1454+
into `ErlangError`:
1455+
1456+
try do
1457+
:erlang.error(:unknown)
1458+
rescue
1459+
ErlangError -> :ok
1460+
end
1461+
1462+
In fact, ErlangError can be used to rescue any error that is
1463+
not an Elixir error proper. For example, it can be used to rescue
1464+
the earlier `:badarg` error too, prior to transformation:
1465+
1466+
try do
1467+
:erlang.error(:badarg)
1468+
rescue
1469+
ErlangError -> :ok
1470+
end
1471+
1472+
## Catching throws and exits
14431473
1444-
The catch clause works exactly the same as in erlang. Therefore,
1445-
one can also handle exits/errors coming from Erlang as below:
1474+
The catch clause can be used to catch throws values and exits.
14461475
14471476
try do
14481477
exit(1)
@@ -1451,14 +1480,14 @@ defmodule Kernel.SpecialForms do
14511480
end
14521481
14531482
try do
1454-
error(:sample)
1483+
throw(:sample)
14551484
catch
1456-
:error, :sample ->
1457-
IO.puts "sample error"
1485+
:throw, :sample ->
1486+
IO.puts "sample thrown"
14581487
end
14591488
1460-
Although the second form should be avoided in favor of raise/rescue
1461-
control mechanisms.
1489+
catch values also support `:error`, as in Erlang, although it is
1490+
commonly avoided in favor of raise/rescue control mechanisms.
14621491
14631492
## Else clauses
14641493

0 commit comments

Comments
 (0)