exceptions.txt 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. Exception handling
  2. ==================
  3. Try statement
  4. -------------
  5. Example:
  6. .. code-block:: nim
  7. # read the first two lines of a text file that should contain numbers
  8. # and tries to add them
  9. var
  10. f: File
  11. if open(f, "numbers.txt"):
  12. try:
  13. var a = readLine(f)
  14. var b = readLine(f)
  15. echo "sum: " & $(parseInt(a) + parseInt(b))
  16. except OverflowError:
  17. echo "overflow!"
  18. except ValueError:
  19. echo "could not convert string to integer"
  20. except IOError:
  21. echo "IO error!"
  22. except:
  23. echo "Unknown exception!"
  24. finally:
  25. close(f)
  26. The statements after the ``try`` are executed in sequential order unless
  27. an exception ``e`` is raised. If the exception type of ``e`` matches any
  28. listed in an ``except`` clause the corresponding statements are executed.
  29. The statements following the ``except`` clauses are called
  30. `exception handlers`:idx:.
  31. The empty `except`:idx: clause is executed if there is an exception that is
  32. not listed otherwise. It is similar to an ``else`` clause in ``if`` statements.
  33. If there is a `finally`:idx: clause, it is always executed after the
  34. exception handlers.
  35. The exception is *consumed* in an exception handler. However, an
  36. exception handler may raise another exception. If the exception is not
  37. handled, it is propagated through the call stack. This means that often
  38. the rest of the procedure - that is not within a ``finally`` clause -
  39. is not executed (if an exception occurs).
  40. Try expression
  41. --------------
  42. Try can also be used as an expression; the type of the ``try`` branch then
  43. needs to fit the types of ``except`` branches, but the type of the ``finally``
  44. branch always has to be ``void``:
  45. .. code-block:: nim
  46. let x = try: parseInt("133a")
  47. except: -1
  48. finally: echo "hi"
  49. To prevent confusing code there is a parsing limitation; if the ``try``
  50. follows a ``(`` it has to be written as a one liner:
  51. .. code-block:: nim
  52. let x = (try: parseInt("133a") except: -1)
  53. Except clauses
  54. --------------
  55. Within an ``except`` clause, it is possible to use
  56. ``getCurrentException`` to retrieve the exception that has been
  57. raised:
  58. .. code-block:: nim
  59. try:
  60. # ...
  61. except IOError:
  62. let e = getCurrentException()
  63. # Now use "e"
  64. Note that ``getCurrentException`` always returns a ``ref Exception``
  65. type. If a variable of the proper type is needed (in the example
  66. above, ``IOError``), one must convert it explicitly:
  67. .. code-block:: nim
  68. try:
  69. # ...
  70. except IOError:
  71. let e = (ref IOError)(getCurrentException())
  72. # "e" is now of the proper type
  73. However, this is seldom needed. The most common case is to extract an
  74. error message from ``e``, and for such situations it is enough to use
  75. ``getCurrentExceptionMsg``:
  76. .. code-block:: nim
  77. try:
  78. # ...
  79. except IOError:
  80. echo "I/O error: " & getCurrentExceptionMsg()
  81. Defer statement
  82. ---------------
  83. Instead of a ``try finally`` statement a ``defer`` statement can be used.
  84. Any statements following the ``defer`` in the current block will be considered
  85. to be in an implicit try block:
  86. .. code-block:: nim
  87. var f = open("numbers.txt")
  88. defer: close(f)
  89. f.write "abc"
  90. f.write "def"
  91. Is rewritten to:
  92. .. code-block:: nim
  93. var f = open("numbers.txt")
  94. try:
  95. f.write "abc"
  96. f.write "def"
  97. finally:
  98. close(f)
  99. Top level ``defer`` statements are not supported
  100. since it's unclear what such a statement should refer to.
  101. Raise statement
  102. ---------------
  103. Example:
  104. .. code-block:: nim
  105. raise newEOS("operating system failed")
  106. Apart from built-in operations like array indexing, memory allocation, etc.
  107. the ``raise`` statement is the only way to raise an exception.
  108. .. XXX document this better!
  109. If no exception name is given, the current exception is `re-raised`:idx:. The
  110. `ReraiseError`:idx: exception is raised if there is no exception to
  111. re-raise. It follows that the ``raise`` statement *always* raises an
  112. exception.
  113. Exception hierarchy
  114. -------------------
  115. The exception tree is defined in the `system <system.html>`_ module:
  116. .. include:: ../exception_hierarchy_fragment.txt