Nirjhar
Nirjhar

Reputation: 1

How to handle 'index out of bounds error' in C++?

The following code segment produces an 'index out of bounds' error. I know the source of this error. I was wondering if there is a way to make the program display the values of indices[I],normpar[I] and normxpar[I] when the the 'index out of bounds' error is produced. That would've helped me a lot with narrowing down the source of error.

for (I = 0; I < 100; I++) norm2par[I] = (normxpar[I] - discvec[indices[I]]);

Upvotes: 0

Views: 679

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69912

void foo(std::vector<int>& norm2par, 
         std::vector<int>& normxpar,
         std::vector<std::size_t>& indices,
         std::vector<int>& discvec)
{
    std::size_t I;

    try
    {
        for (I = 0; I < 100; I++) 
        {
            norm2par.at(I) = (normxpar.at(I) - discvec.at(indices.at(I)));
        }
    }
    catch(...)
    {
        std::ostringstream ss;
        ss << __func__ << " throw with I=" << I;
        std::throw_with_nested(std::logic_error(ss.str()));
    }
}

Upvotes: 1

Related Questions