Coverity defect highlighted possible use of negative index to array. Prevent this by throwing an out-of-range error instead. Update unit tests to cope.