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:
  13. echo "could not convert string to integer"
  14. except IOError:
  15. echo "IO error!"
  16. except:
  17. echo "Unknown exception!"
  18. finally:
  19. 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.

The empty except clause is executed if there is an exception that is not listed otherwise. It is similar to an else clause in if statements.

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).