Catching Range Error when trying to use getItemAt for ArrayCollection

If you have ever been doing some work with ArrayCollections, you must have seen Flash Range Error when trying to use getItemAt method on ArrayCollection if there is no entry for the index provided.

For example:

private var myAC:ArrayCollection = new ArrayCollection();
myAC.addItem({key1: 'value1', key2: 'value2', key3: 'value3'});

trace (myAC.getItemAt(0).key1) //returns value1

trace (myAC.getItemAt(1).key1) //you get Range Error: Index '1' specified is out of bounds

So how can we ensure that we don’t get a Range Error when we try to access an index in arraycollection that does not exist. We can use try catch, so we try to getItemAt some index and then we catch if we get an error.

Going back to the previous example

private var myAC:ArrayCollection = new ArrayCollection();
myAC.addItem({key1: 'value1', key2: 'value2', key3: 'value3'});
try {
trace (myAC.getItemAt(0).key1) //returns value1

trace (myAC.getItemAt(1).key1) //will not generate a general error but will go into the catch and trace index is out of bounds
} 
catch (e:RangeError){
	trace('index is out of bounds');
}

This time around we wont get an Range Error, rather after Flash will encounter Range Error it will go into the catch block and execute any code that is written there, in our case, just tracing that index is out of bounds.

I would recommend doing try catch when using getItemAt, because it can quickly happen that we want to access and index that is not in the ArrayCollection.

Happy coding 🙂

Advertisements

, , , , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: