Try statement

Example:

  1. # read the first two lines of a text file that should contain numbers
  2. # and tries to add them
  3. var
  4. f: File
  5. if open(f, "numbers.txt"):
  6. try:
  7. var a = readLine(f)
  8. var b = readLine(f)
  9. echo "sum: " & $(parseInt(a) + parseInt(b))
  10. except OverflowDefect:
  11. echo "overflow!"
  12. except ValueError, IOError:
  13. echo "catch multiple exceptions!"
  14. except CatchableError:
  15. echo "Catchable exception!"
  16. finally:
  17. close(f)

The statements after the try are executed in sequential order unless an exception e is raised. If the exception type of e matches any listed in an except clause, the corresponding statements are executed. The statements following the except clauses are called exception handlers.

If there is a finally clause, it is always executed after the exception handlers.

The exception is consumed in an exception handler. However, an exception handler may raise another exception. If the exception is not handled, it is propagated through the call stack. This means that often the rest of the procedure - that is not within a finally clause - is not executed (if an exception occurs).