Navigation
Synopsis Index is out of bounds.
Function data RunTimeException = IndexOutOfBounds(int index);
Usage import Exception;
Description Subscription is possible on various ordered types, including Rascal:List/Subscription, Rascal:Tuple/Subscription, and Rascal:Node/Subscription. 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 Rascal:List/index to produce all legal indices of a list. Instead of for(int i <- [0..size(L)]) { ... } use for(int i <- index(L)) { ... }.
    • Use a Rascal:Values/List/Slice to automate part of the index computation.
  • Catch the IndexOutOfBounds yourself, see Rascal:TryCatch.
Examples 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];
|stdin:///|(2,1,<1,2>,<1,3>): IndexOutOfBounds(5)
	at ___SCREEN_INSTANCE___(|stdin:///|(0,5,<1,0>,<1,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
ok
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.