![]() |
|
Navigation |
Synopsis Try to execute a statement and catch resulting exceptions.
Syntax
try Statement1; catch PatternWithAction1; catch PatternWithAction2; ... catch: Statement2; finally: Statement3;
Description A try catch statement has as purpose to catch any Exceptions that are raised during the execution of
Statement1 .
These exceptions may caused by:
Examples Let's define a variant of the head function that returns the first element of a list,
but throws an exception when the list is empty. Our variant will return
0 for an empty list:
rascal>import List; ok rascal>import Exception; ok rascal>int hd(list[int] x) { try return head(x); catch: return 0; } int (list[int]): int hd(list[int]); rascal>hd([1,2,3]); int: 1 rascal>hd([]); int: 0We can also be more specific and catch the EmptyList exception
(which is available here since we have imported the Exception module):
rascal>int hd2(list[int] x) { try return head(x); catch EmptyList(): return 0; } int (list[int]): int hd2(list[int]); rascal>hd2([]); int: 0 ![]() |