Index Out Of Bounds
rascal-0.41.2
Synopsis
Index is out of bounds.
Types
data RuntimeException = IndexOutOfBounds(int index)
Usage
import Exception; (only needed when IndexOutOfBounds is used in catch)
Description
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.
- Use the index to produce all legal indices of a list.
Instead of
- Catch the
IndexOutOfBoundsyourself, see try catch.
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];
|prompt:///|(2,1,<1,2>,<1,3>): IndexOutOfBounds(5)
at $(|prompt:///|(0,5,<1,0>,<1,5>))
We can catch the IndexOutOfBounds error. First import the Rascal exceptions (which are also included in Prelude) and import IO for Println:
rascal>import Exception;
ok
rascal>import IO;
ok
rascal>try
|1 >>>> L[5];
|2 >>>>catch IndexOutOfBounds(msg):
|3 >>>> println("The message is: <msg>");
The message is: 5
ok