No Such Key
rascal-0.41.2
Synopsis
A map does not contain a requested key.
Types
data RuntimeException = NoSuchKey(value v);
Usage
import Exception; (only needed when NoSuchKey is used in catch)
Description
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.
Examples
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"]
|prompt:///|(2,3,<1,2>,<1,5>): NoSuchKey("c")
at $(|prompt:///|(0,23,<1,0>,<1,23>))
Use the postfix isDefined operator ? to test whether the value is defined:
rascal>if (M["c"]?) {
|1 >>>> println("defined");
|2 >>>>} else {
|3 >>>> println("not defined");
|4 >>>>}
not defined
ok
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
|1 >>>> println(M["c"]);
|2 >>>>catch NoSuchKey(k):
|3 >>>> println("Key <k> does not exist");
Key c does not exist
ok