@@ -1377,7 +1377,7 @@ defmodule Kernel.SpecialForms do
1377
1377
"""
1378
1378
defmacro case ( condition , blocks )
1379
1379
1380
- @ doc """
1380
+ @ doc ~S """
1381
1381
Evaluate the given expressions and handle any error, exit
1382
1382
or throw that may have happened.
1383
1383
@@ -1390,10 +1390,10 @@ defmodule Kernel.SpecialForms do
1390
1390
IO.puts "Invalid argument given"
1391
1391
catch
1392
1392
value ->
1393
- IO.puts "caught \ # {value}"
1393
+ IO.puts "caught #{value}"
1394
1394
else
1395
1395
value ->
1396
- IO.puts "Success! The result was \ # {value}"
1396
+ IO.puts "Success! The result was #{value}"
1397
1397
after
1398
1398
IO.puts "This is printed regardless if it failed or succeed"
1399
1399
end
@@ -1439,10 +1439,39 @@ defmodule Kernel.SpecialForms do
1439
1439
x -> nil
1440
1440
end
1441
1441
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
1443
1473
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.
1446
1475
1447
1476
try do
1448
1477
exit(1)
@@ -1451,14 +1480,14 @@ defmodule Kernel.SpecialForms do
1451
1480
end
1452
1481
1453
1482
try do
1454
- error (:sample)
1483
+ throw (:sample)
1455
1484
catch
1456
- :error , :sample ->
1457
- IO.puts "sample error "
1485
+ :throw , :sample ->
1486
+ IO.puts "sample thrown "
1458
1487
end
1459
1488
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.
1462
1491
1463
1492
## Else clauses
1464
1493
0 commit comments