Thursday, October 14, 2010

Cause of exception "Index and length must refer to a location within the string"

Every once in a while, my .NET 2.0 website would throw this exception: "Index and length must refer to a location within the string." I knew this because I could see the exception in the Windows application event log, but the log didn't give a line number or any other information that allowed me to narrow it down to less than a few hundred lines of code.

By adding a bunch of logging -- trapping exceptions with lots of try/catch blocks and writing them to disk -- I found the problem. This exception can occur when you call the .NET String.Substring() method and the string's length is not long enough.

Something like this would cause it:
string s = "abc";
string s2 = s.Substring(1,5);

In my case, I was parsing a credit card expiration date on the assumption that it would always be formatted as mm/yyyy, but it turned out sometimes the month was a single digit, as in 6/2013 rather than 06/2013.

No comments:

Post a Comment