Search code examples
exceptionrascal

curious: Why is IndexOutOfBounds exception different from emptyList exception in Rascal?


Consider calling function foobar with arguments,

list[int] exampleA=[1,2,3];
list[int] exampleB=[];

//call with under-sized list
foobar(exampleA); //everything ok, exception caught and handled

//call with empty list
foobar(exampleB); //throws an exception: emptyList

public void foobar(list[int] intList)
{
  try
  {
    int i=0;
    while(i<=5)
    {
        println(intList[i]);
        i++;
    }
  }
  catch IndexOutOfBounds(msg):
  {
    //do something
  }
}

Shouldn't IndexOutOfBounds technically be same as emptyList? What maybe the reason that these situations are considered two different exception conditions?


Solution

  • Good question.

    The exception EmptyList addresses the case where a function or operator expects a non-empty list as argument. For instance, taking the head of an empty list, as in head([]), gives this exception.

    The exception IndexOutOfBounds is always associated with an illegal indexing operation on a list (list), list relation (lrel), string (str), or tuple (tuple) and involves an illegal index. This exception carries as extra information the offending index.

    We make the distinction because for the EmptyList exception there is no clear offending index to report: the two exceptions carry therefore different information.