Exactly why is up to your data, but the mechanics of getting the problem are simple:
What happens if the end is found before the start, or as part of the start string?
I.e. if input is "1234567890" and start is "345678" and end is "23", then
index1 == 8
index2 == 1
So your length will be negative. That won't cause the exact error you are getting this time, but it's an example of a "route to failure" which depends on your data to work out exactly what the problem is.
If you get a problem like this, use the debugger, and look at your data. Step through line by line and try to spot what values are what.