pull the index bounds checking code out into a utility method, improving the exception messages in the process