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:
  • The execution of an explicit Throw statement.
  • The Rascal system that discovers an abnormal condition, e.g., an out of bounds error when accessing a list element.
Note that all elements of the try catch statement are optional but that at least one has to be present. Their meaning is as follows:
  • If a pattern of some PatternWithActioni matches, the corresponding action is executed.
  • Otherwise, Statement2 is executed (when present).
  • Before leaving the try catch statement Statement3 is always executed (when present).
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: 0
We 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
Is this page unclear, or have you spotted an error? Please add a comment below and help us to improve it. For all other questions and remarks, visit ask.rascal-mpl.org.