Wrong Line highlighted on IndexOutOfRangeException
I have a test code I wrote up in LINQPad that involves iterating through arrays. When I get an IndexOutOfRangeException, it seems to be highlighting a random array. I'm more interested in the actual line of code that triggered the exception.
Here is the sample code I am working with: http://share.linqpad.net/wv2duj.linq
If you run this code, you'll get the exception, and note that it highlights the following line #10:
var combinedInts = new List();
I had to copy the code into a new Visual Studio project and run it to figure out the actual line generating the error, which is this line #43:
if (loopCounters[lastCounter] < numInts) tempSum -= listOfInts[loopCounters[lastCounter]];
I'm not sure if this is intentional, but it is confusing. I would expect the actual line causing the exception to be highlighted when there is an exception in running the code.
I tested this in both the latest version of LINQPad 4 and LINQPad 5, as well as putting all the code into a single method body instead of a separate function. In every case I get the same behavior, just different arrays highlighted, but never the actual line that generated the exception.
Any ideas??
Here is the sample code I am working with: http://share.linqpad.net/wv2duj.linq
If you run this code, you'll get the exception, and note that it highlights the following line #10:
var combinedInts = new List();
I had to copy the code into a new Visual Studio project and run it to figure out the actual line generating the error, which is this line #43:
if (loopCounters[lastCounter] < numInts) tempSum -= listOfInts[loopCounters[lastCounter]];
I'm not sure if this is intentional, but it is confusing. I would expect the actual line causing the exception to be highlighted when there is an exception in running the code.
I tested this in both the latest version of LINQPad 4 and LINQPad 5, as well as putting all the code into a single method body instead of a separate function. In every case I get the same behavior, just different arrays highlighted, but never the actual line that generated the exception.
Any ideas??
Comments
I'll add a feature to the next build that will warn you when this happens.
This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than or equal to the number of elements it contains. Indexing an empty list will always throw an exception. Use a method like Add to append the item to the end of the list, or Insert to place the item in the middle of the list somewhere, etc. You cannot index into a list if that offset doesn't exist. IndexOutOfRangeException exception is thrown as a result of developer error. Instead of handling the exception, you should diagnose the cause of the error and correct your code.