Try statement
Example:
# read the first two lines of a text file that should contain numbers
# and tries to add them
var
f: File
if open(f, "numbers.txt"):
try:
var a = readLine(f)
var b = readLine(f)
echo "sum: " & $(parseInt(a) + parseInt(b))
except OverflowDefect:
echo "overflow!"
except ValueError:
echo "could not convert string to integer"
except IOError:
echo "IO error!"
except:
echo "Unknown exception!"
finally:
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).