All exceptions and errors a Rascal program can generate during execution (run time).
Rascal can generate various kinds of exceptions and errors during execution (run time):
-
Runtime Exceptions are discovered during execution of the Rascal program and can be caught by the Rascal program. When a runtime exception is not caught in the program, execution is aborted.
-
Other Runtime Errors are discovered during execution of the Rascal program and cannot be caught by the Rascal program. They always lead to abortion of execution.
The structure and naming of exceptions and error messages is being revised so actual exceptions may differ from what is presented here.
1. Runtime Exceptions
All runtime exceptions that can occur during execution of a Rascal program.
The following exceptions can be trown as the result of a run-time error:
-
Ambiguity: Ambiguity found in parsed text.
-
Arithmetic Exception: An arithmetic exception occurred.
-
Assertion Failed: An assertion in the Rascal code is false.
-
Empty List: Illegal operation on an empty list.
-
Empty Map: Illegal operation on an empty set.
-
Empty Set: Illegal operation on an empty set.
-
IO: An input/output operation caused an error.
-
Index Out Of Bounds: Index is out of bounds.
-
Invalid Argument: A function or operation is applied to an invalid argument value.
-
Invalid URI: An invalid URI is created at runtime.
-
Invalid Use Of Date: Invalid of of a date at runtime.
-
Invalid Use Of Location: Invalid use of a source location at runtime.
-
Invalid Use Of Time: Invalid use of a time value at runtime.
-
Java: Runtime error generated by Java code.
-
No Main Function: Rascal program does not provide a
mainfunction. -
No Parent: Parent directory is missing in source location.
-
No Such Annotation: Annotation without a value.
-
No Such Field: Field of an abstract data type value cannot be found at runtime.
-
No Such Key: A map does not contain a requested key.
-
Not Implemented: Attempt to execute an unimplemented feature.
-
Parse Error: Parse of a syntactically incorrect string.
-
RegExp Syntax Error: Syntax error in regular expression at run time.
-
Unavailable Information: Requested information is unavailable at runtime.
1.1. Ambiguity
Ambiguity found in parsed text.
Rascal supports general context-free grammars and also provides various mechanisms to disambiguate them.
This exception is thrown when, given a grammar and a sentence, an ambiguity is found while parsing the sentence according to that grammar.
First declare a very simple expression language that should
recognize expressions like a, a+a, a+(a+a):
rascal>syntax A = "a";
ok
rascal>syntax E = A | "(" E ")" | E "+" E;
ok
Next, import the ParseTree module that provides a parse function that we will use:
rascal>import ParseTree;
ok
Entering a first expression goes well:
rascal>parse(#E, "a+a");
E: (E) `a+a`
However, when becoming more ambitious, we get an exception:
rascal>parse(#E, "a+a+a");
Error: Ambiguity(|unknown:///|(0,5,<1,0>,<1,5>),"E","a+a+a")
The conclusion is that there are two parses here: a+(a+a) and (a+a)+a,
because we did forget to define the associativity of the + operator.
Let’s fix this:
rascal>syntax A = "a";
ok
rascal>syntax E = A | "(" E ")" | left E "+" E;
ok
rascal>import ParseTree;
ok
rascal>parse(#E, "a+a+a");
E: (E) `a+a+a`
Here are some pointers for further disambiguation help:
1.2. Arithmetic Exception
An arithmetic exception occurred.
data RuntimeException = ArithmeticException(str message);
import Exception; (only needed when ArithmeticException is used in catch)
This error is generated when an illegal arithmetic operation occurs or when a numeric function is called with an out-of-range argument.
Remedies:
-
Check the validity of the argument before you call the function or apply the operator.
-
Catch the
ArithmeticExceptionyourself, see try catch statement.
Division by 0 gives an error:
rascal>3/0;
Error: ArithmeticException("divide by zero")
Giving an out-of-range argument to a mathematical function also gives an error:
rascal>import util::Math;
ok
rascal>tan(-550000000000000000000000);
Error: ArithmeticException("x should be between -(pi/2) and (pi/2)")
We can also catch the ArithmeticException error. First import the Rascal exceptions (which are also included in Prelude)
and IO:
rascal>import Exception;
ok
rascal>import IO;
ok
rascal>try println(3/0); catch ArithmeticException(msg): println("The message is: <msg>");
The message is: divide by zero
1.3. Assertion Failed
An assertion in the Rascal code is false.
data RuntimeException = AssertionFailed(str label);
An Assert statement can be used to check assumptions during the execution of a Rascal program. This error is generated if an assertion is not true.
Remedies:
-
Modify your code to make the assertion true.
-
Modify your assertion to reflect the current behaviour of your code.
-
Catch the
AssertionFailedyourself, see try catch.
A false assertion gives an error:
rascal>assert 3 > 4;
Error: AssertionFailed("")
Define a function that only increments positive integers:
rascal>int incrPositive(int n) { assert n > 0: "n should be greater than 0"; return n + 1; }
ok
Calling it with a positive integer is fine:
rascal>incrPositive(3);
int: 4
But a negative argument gives an error:
rascal>incrPositive(-3);
Error: AssertionFailed("n should be greater than 0")
We can also catch the AssertionFailed error. First import the Rascal exceptions (which are also included in Prelude)
and IO:
rascal>import Exception;
ok
rascal>import IO;
ok
rascal>try println(incrPositive(-3)); catch AssertionFailed(msg): println("incrPositive: <msg>");
incrPositive: n should be greater than 0
-
Enables the precise expression of assumptions in your code.
-
Asserts are actually executed when the compiler option
enableAssertsis set to true (by default set tofalse). -
In the RascalShell,
enableAssertsis always true.
1.4. Empty List
Illegal operation on an empty list.
data RuntimeException = EmptyList();
import Exception; (only needed when EmptyList is used in catch)
Rascal provides many operations and functions on lists, see list values and list functions. This error is generated when a function or operation cannot handle the empty list.
Remedies:
Import the List library and introduce L with an empty list as value:
rascal>import List;
ok
rascal>L = [];
list[void]: []
Taking the head of an empty list gives an error:
rascal>head(L);
Error: EmptyList()
This is the case when taking the tail as well:
rascal>tail(L);
Error: EmptyList()
We can also catch the EmptyList error. First import the Rascal exceptions (which are also included in Prelude)
and IO:
rascal>import Exception;
ok
rascal>import IO;
ok
rascal>try println(head(L)); catch EmptyList(): println("Cannot take head of empty list");
Cannot take head of empty list
1.5. Empty Map
Illegal operation on an empty set.
data RuntimeException = EmptyMap();
import Exception; (only needed when EmptyMap is used in catch)
Rascal provides many operations and functions on maps, see map values and map functions. This error is generated when a function or operations cannot handle the empty map.
Remedies:
Import the Map library and introduce M with an empty map as value:
rascal>import Map;
ok
rascal>M = ();
map[void, void]: ()
Trying to get an arbitrary value from it gives an error:
rascal>getOneFrom(M);
Error: EmptyMap()
We can also catch the EmptyMap error. First import the Rascal exceptions (which are also included in Prelude)
and IO:
rascal>import Exception;
ok
rascal>import IO;
ok
rascal>try println(getOneFrom(M)); catch EmptyMap(): println("Cannot use getOneFrom on empty map");
Cannot use getOneFrom on empty map
1.6. Empty Set
Illegal operation on an empty set.
data RuntimeException = EmptySet();
import Exception; (only needed when EmptySet is used in catch)
Rascal provides many operations and functions on sets, see set values and set functions. This error is generated when a function or operations cannot handle the empty set.
Remedies:
Import the Set library and introduce S with an empty set as value:
rascal>import Set;
ok
rascal>S = {};
set[void]: {}
Taking an element from an empty set gives an error:
rascal>getOneFrom(S);
Error: EmptySet()
We can also catch the EmptySet error. First import the Rascal exceptions (which are also included in Prelude)
and IO:
rascal>import Exception;
ok
rascal>import IO;
ok
rascal>try println(getOneFrom(S)); catch EmptySet(): println("Cannot apply getOneFrom to empty set");
Cannot apply getOneFrom to empty set
1.7. IO
An input/output operation caused an error.
data RuntimeException = IO(str message);
import Exception; (only needed when IO is used in catch)
This error can be generated for many reasons.
First there may be a problem in the location that is used.
It maybe that the schemes is not supported.
Examples of supported schemes include http, file, home, std, rascal and project.
It can also be the case that the host that occurs in the location cannot be found.
Second, while trying to open the file things can go wrong like insufficient access rights
Finally, actual reading or writing can fail (device failure, device full, and the like).
Remedies:
-
Check for any errors in the location you are using.
-
Check that you are allowed to read or write the resource indicated by the location.
-
Catch
IOusing a try catch.
Import the IO library and attempt to use a non-existing scheme:
rascal>import IO;
ok
rascal>readFile(|myScheme:///example.rsc|);
Error: IO("Unsupported scheme myScheme")
We can catch this IO error. First import the Rascal exceptions (which are also included in Prelude):
rascal>import Exception;
ok
rascal>try readFileLines(|myScheme:///example.rsc|); catch IO(msg): println("This did not work: <msg>");
This did not work: Unsupported scheme myScheme
1.8. Index Out Of Bounds
Index is out of bounds.
data RuntimeException = IndexOutOfBounds(int index)
import Exception; (only needed when IndexOutOfBounds is used in catch)
Subscription is possible on various ordered types, including list, tuple, and node. This error is generated when a subscript is out of bounds for the value that is being subscripted.
Remedies:
-
Guard the subscription with a test that the index is within bounds.
-
Make your code less dependent on index values. Suggestions:
-
Use the index to produce all legal indices of a list. Instead of
for(int i ← [0..size(L)]) { … }usefor(int i ← index(L)) { … }. -
Use a list slice to automate part of the index computation.
-
-
Catch the
IndexOutOfBoundsyourself, see try catch.
Initialize a list L:
rascal>L = [0, 10, 20, 30, 40];
list[int]: [0,10,20,30,40]
The legal indices are 0, 1, 2, 3, 4, so index 5 gives an error:
rascal>L[5];
Error: IndexOutOfBounds(5)
We can catch the IndexOutOfBounds error. First import the Rascal exceptions (which are also included in Prelude)
and IO:
rascal>import Exception;
ok
rascal>import IO;
ok
rascal>try L[5]; catch IndexOutOfBounds(msg): println("The message is: <msg>");
The message is: 5
1.9. Invalid Argument
A function or operation is applied to an invalid argument value.
data RuntimeException = InvalidArgument() | InvalidArgument(value v) | InvalidArgument(value v, str message);
import Exception; (only needed when InvalidArgument is used in catch)
This error is generated when a function or operation is applied to a value that it does not expect.
Remedies:
-
Check the value or values to which you apply the function or operation.
Changing the month of a DateTime to an illegal month (13):
rascal>NOW = $2013-01-13T22:16:51.740+01:00$;
datetime: $2013-01-13T22:16:51.740+01:00$
rascal>NOW.month = 13;
Error: InvalidArgument($2013-01-13T22:16:51.740+01:00$,"Cannot create datetime with provided values.")
Setting the offset in a location to a negative value:
rascal>someLoc = |home:///abc.txt|;
loc: |home:///abc.txt|
rascal>someLoc.offset = -1;
Error: InvalidArgument()
1.10. Invalid URI
An invalid URI is created at runtime.
data RuntimeException = InvalidURI(str uri);
import Exception; (only needed when InvalidURI is used in catch)
Thrown by operations on source locations that would lead to an invalid URI part of a source location value.
rascal>someLoc = |home:///abc.txt|;
loc: |home:///abc.txt|
rascal>someLoc.scheme = "a:b";
Error: InvalidURI("Scheme is not a valid scheme: a:b")
Another well-known example is a missing path when using // (wrong) instead of /// (good):
rascal>|home:///|;
loc: |home:///|
rascal>|home://|;
Error: InvalidURI("home://")
1.11. Invalid Use Of Date
Invalid of of a date at runtime
data RuntimeException = InvalidUseOfDate(str message);
import Exception; (only needed when InvalidUseOfDate is used in catch)
Thrown by operations on date values that try to update unavailable information.
Setting the hour field on a date value throws an exception:
rascal>NOW = $2016-09-18$;
datetime: $2016-09-18$
rascal>NOW.hour = 14;
Error: Cannot get hours on a date value
| Exception is not shown properly |
1.12. Invalid Use Of Location
Invalid use of a source location at runtime.
data RuntimeException = InvalidUseOfLocation(str message);
import Exception; (only needed when InvalidUseOfLocation is used in catch)
Thrown by operations on source locations that would lead to an inconsistent or incomplete location value.
rascal>someLoc = |home:///abc.txt|;
loc: |home:///abc.txt|
rascal>someLoc.begin = <1, 2>;
Error: InvalidUseOfLocation("Can not add line/column information without offset/length")
1.13. Invalid Use Of Time
Invalid use of a time value at runtime
data RuntimeException = InvalidUseOfTime(str message);
import Exception; (only needed when InvalidUseOfTime is used in catch)
Thrown by operations on time values that try to update unavailable information.
Setting the year field on a time value throws an exception:
rascal>NOW = $T20:11:01.463+00:00$;
datetime: $T20:11:01.463+00:00$
rascal>NOW.year = 2020;
Error: Cannot get year on a time value
| Exception is not shown properly |
1.14. Java
Runtime error generated by Java code.
This error is generated when an unexpected Java execption is thrown in the Rascal implementation.
Remedy: Contact the Rascal developers:
-
Ask a question at http://stackoverflow.com/questions/tagged/rascal.
-
Read the currently open issues at the Rascal’s issue tracker at https://github.com/cwi-swat/rascal/issues?state=open. If your problem has not yet been reported by someone else, please report it here.
If you are an expert developer and have implemented your own extension in Java, please check your own extension code first.
1.15. No Main Function
Rascal program does not provide a main function.
data RuntimeException = NoMainFunction(str message);
import Exception; (only needed when NoMainFunction is used in catch)
Thrown when executing a Rascal program that does not declare a main function.
1.16. No Parent
Parent directory is missing in source location.
data RuntimeException = NoParent(loc noparentloc);
import Exception; (only needed when NoParent is used in catch)
1.17. No Such Annotation
Annotation without a value.
data RuntimeException = NoSuchAnnotation(str label);
import Exception; (only needed when NoSuchAnnotation is used in catch)
An annotation can be associated with any node value (including any algebraic data type). This error is generated when the value of an annotation is requested but has not been defined.
Remedies:
-
Ensure that the annotation value is properly initialized for all relevant parts of the node value.
-
Use the isDefined and ifDefinedElse operators to check whether the annotation value is set and act accordingly.
-
Catch the
NoSuchAnnotation yourself, see try catch.
INFO: Eliminate the double Error: Error:
rascal>data Fruit = apple(int n) | orange(int n);
ok
rascal>anno str Fruit @ quality;
Error: Not supported construct: anno str Fruit @ quality;
rascal>piece = orange(13);
Fruit: orange(13)
rascal>piece@quality;
Error: Error: Annotation quality not declared on Fruit or its supertypes IN 'piece@quality'
Use the unary postfix operator isDefined ? to check whether the quality annotation is set:
rascal>piece@quality?;
Error: Error: Annotation quality not declared on Fruit or its supertypes IN 'piece@quality'
Use the ternary operator ifDefinedElse ? to compute an alternative value when the quality annotation is not set:
rascal>piece@quality ? "no quality value";
Error: Error: Annotation quality not declared on Fruit or its supertypes IN 'piece@quality'
We can also catch the NoSuchAnnotation error. First import the Rascal exceptions (which are also included in Prelude)
and IO:
rascal>import Exception;
ok
rascal>import IO;
ok
rascal>try piece@quality; catch NoSuchAnnotation(l): println("No such annotation: <l>");
Error: Error: Annotation quality not declared on Fruit or its supertypes IN 'piece@quality'
Finally, we can just assign a value to the quality annotation:
rascal>piece@quality = "excellent";
str: "excellent"
rascal>piece@quality;
Error: Error: Annotation quality not declared on Fruit or its supertypes IN 'piece@quality'
|
Pitfalls
Using white space around the @ confuses the Rascal parser
|
1.18. No Such Field
Field of an abstract data type value cannot be found at runtime.
data RuntimeException = NoSuchField(str name);
import Exception; (only needed when NoSuchField is used in catch)
Selecting a field from an abstract datatype depends on the actual constructor being used at run time. This exception is thrown when a non-existent field is accessed.
Consider this highly simplified view on persons:
rascal>data Person = man(str name, bool beard) | woman(str name, bool necklace);
ok
rascal>jane = woman("jane", false);
Person: woman("jane",false)
The field beard is evidently only applicable to a man but not to a woman
(didn’t we say "simplified", above):
rascal>jane.beard;
Error: NoSuchField("beard")
1.19. No Such Key
A map does not contain a requested key.
data RuntimeException = NoSuchKey(value v);
import Exception; (only needed when NoSuchKey is used in catch)
Rascal provides many operations and functions on maps, see map values and map functions. This error is generated when a function or operation cannot find a requested key value in a map.
Remedies:
-
Use the isDefined and ifDefinedElse operator to guard a lookup in a map.
-
Catch the
NoSuchKeyyourself, see try catch.
Import the Map and IO libraries and introduce map M:
rascal>import Map;
ok
rascal>import IO;
ok
rascal>M = ("a" : 1, "b" : 2);
map[str, int]: ("a":1,"b":2)
Indexing M with a non-existing key gives an error:
rascal>M["c"]
Error: NoSuchKey("c")
Use the postfix isDefined operator ? to test whether the value is defined:
rascal>if(M["c"]?) println("defined"); else println("not defined");
not defined
Or use the binary ifDefinedElse operator ? to return an alternative value
when the value of M["c"] is undefined:
rascal>M["c"] ? 3
int: 3
Yet another solution is to use try/catch.
First we import the Rascal exceptions (which are also included in Prelude):
rascal>import Exception;
ok
rascal>try println(M["c"]); catch NoSuchKey(k): println("Key <k> does not exist");
Key c does not exist
1.20. Not Implemented
Attempt to execute an unimplemented feature.
data RuntimeException = NotImplemented(str msg), loc src);
import Exception; (only needed when NotImplemented is used in catch)
Thrown when a not (yet) implemented feature is executed. This exception is mostly used by the Rascal implementors.
1.21. Parse Error
Parse of a syntactically incorrect string.
data RuntimeException = ParseError(loc parseloc) | ParseError(loc parseloc, str nt, str s);
import Exception; (only needed when ParseError is used in catch)
This error is generated when during the execution of a Rascal program the parse function is applied to a syntactically incorrect input sentence.
Remedies:
-
Correct the input sentence.
-
Adapt the grammar so that it accepts the input sentence.
-
Catch the ParseError yourself, see try catch.
Define the non-terminal As that accepts one or more letters a:
rascal>syntax As = "a"+;
ok
Then import ParseTree so that we can use the parse function:
rascal>import ParseTree;
ok
Now we can parse sentences consisting of letters a:
rascal>parse(#As, "aaaaaaaa");
As: (As) `aaaaaaaa`
But we get an error when parsing syntactically incorrect input (i.e., that does not
consists of letters a only):
rascal>parse(#As, "aaaabaaa");
Error: ParseError(|unknown:///|(4,1,<1,4>,<1,5>))
We can also catch the ParseError but first import the Rascal modules Exception and IO:
rascal>import Exception;
ok
rascal>import IO;
ok
rascal>try parse(#As, "aaaabaaa"); catch ParseError(e): println("Your input cannot be parsed: <e>");
Your input cannot be parsed: |unknown:///|(4,1,<1,4>,<1,5>)
1.22. RegExp Syntax Error
Syntax error in regular expression at run time
data RuntimeException = RegExpSyntaxError(str message);
import Exception; (only needed when RegExpSyntaxError is used in catch)
At the moment, the parsing and compilation of regular expression is done at run time. This exception is thrown when a syntactically incorrect regular expression is used.
The following regular expression /+/ is incorrect (maybe /a+/ was meant?):
rascal>/+/ := "aaaa";
Error: RegExpSyntaxError("+")
1.23. Unavailable Information
Requested information is unavailable at runtime
data RuntimeException = UnavailableInformation(str message);
import Exception; (only needed when UnavailableInformation is used in catch)
Several datetypes may contain optional information that is not always available:
This exception is thrown when optional information is not available.
rascal>$2016-09-14$.hour;
Error: UnavailableInformation("Can not retrieve the hour on a date value")
rascal>someLoc = |home:///abc.txt|;
loc: |home:///abc.txt|
rascal>someLoc.offset;
Error: UnavailableInformation("offset")
2. Other Runtime Errors
Other runtime errors that cannot be caught as a runtime exception.
Note: Examples will be collected here
2.1. Compiler Error
An internal error in the Rascal compiler
An internal error condition occurred while running the Rascal compiler. This exception may be generated due to:
-
An actual internal inconsistency.
-
Incorrect information as computed by the type checker.
-
Incorrect configuration of paths (PathConfig) when calling the compiler.
-
Causes outside control of the compiler.
At the moment this error category is too wide and should be narrowed.