documented 'defer' statement
This commit is contained in:
parent
59e279ba9c
commit
a505918e0c
1 changed files with 17 additions and 22 deletions
|
|
@ -47,36 +47,31 @@ the rest of the procedure - that is not within a ``finally`` clause -
|
||||||
is not executed (if an exception occurs).
|
is not executed (if an exception occurs).
|
||||||
|
|
||||||
|
|
||||||
Standalone except and finally statements
|
Defer statement
|
||||||
----------------------------------------
|
---------------
|
||||||
|
|
||||||
``except`` and ``finally`` can also be used as a stand-alone statements.
|
Instead of a ``try finally`` statement a ``defer`` statement can be used.
|
||||||
Any statements following them in the current block will be considered to be
|
|
||||||
in an implicit try block:
|
Any statements following the ``defer`` in the current block will be considered
|
||||||
|
to be in an implicit try block:
|
||||||
|
|
||||||
.. code-block:: nim
|
.. code-block:: nim
|
||||||
var f = open("numbers.txt")
|
var f = open("numbers.txt")
|
||||||
finally: close(f)
|
defer: close(f)
|
||||||
...
|
f.write "abc"
|
||||||
|
f.write "def"
|
||||||
|
|
||||||
The ``except`` statement has a limitation in this form: one can't specify the
|
Is rewritten to:
|
||||||
type of the exception, one has to catch everything. Also, if one wants to use
|
|
||||||
both ``finally`` and ``except`` one needs to reverse the usual sequence of the
|
|
||||||
statements. Example:
|
|
||||||
|
|
||||||
.. code-block:: nim
|
.. code-block:: nim
|
||||||
proc test() =
|
var f = open("numbers.txt")
|
||||||
raise newException(Exception, "Hey ho")
|
try:
|
||||||
|
f.write "abc"
|
||||||
|
f.write "def"
|
||||||
|
finally:
|
||||||
|
close(f)
|
||||||
|
|
||||||
proc tester() =
|
Top level ``defer`` statements are not supported
|
||||||
finally: echo "3. Finally block"
|
|
||||||
except: echo "2. Except block"
|
|
||||||
echo "1. Pre exception"
|
|
||||||
test()
|
|
||||||
echo "4. Post exception"
|
|
||||||
# --> 1, 2, 3 is printed, 4 is never reached
|
|
||||||
|
|
||||||
Top level standalone ``finally`` or ``except`` statements are not supported
|
|
||||||
since it's unclear what such a statement should refer to.
|
since it's unclear what such a statement should refer to.
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue