Sam
Sam

Reputation: 159

Which vector threw index out of range exception?

I would like to access a reference to the std::vector which throws an out of range exception, or at least the line number where the exception was thrown (similar to Java's stack traces). Here is an example program:

#include <iostream>
#include <vector>
std::vector<int> vec1;
std::vector<int> vec2;
vec1.push_back(1);
vec2.push_back(2);
try
{

    std::cout << vec1.at(1) << std::endl;
    std::cout << vec2.at(1) << std::endl;
}
catch(Exception e)
{
    // e.lineNumber()? e.creator_object()?
    std::cout << "The following vector is out of range: " << ? << std::endl;
    // or...
    std::cout << "There was an error on the following line: " << ? << std::endl;
}

I know this example is trivial, but I hope it demonstrates what functionality I'm looking for.

EDIT: Implementation, from g++ --version: g++ (GCC) 4.1.2 20071124 (Red Hat 4.1.2-42)

Upvotes: 0

Views: 4416

Answers (1)

nvoigt
nvoigt

Reputation: 77294

You will need to do that yourself:

#include <iostream>
#include <vector>

std::vector<int> vec1;
std::vector<int> vec2;

vec1.push_back(1);
vec2.push_back(2);

try
{
    std::cout << vec1.at(1) << std::endl;
}
catch(std::exception& e)
{
    std::cout << "The following vector is out of range: " << "vec1" << std::endl;
}

try
{
    std::cout << vec2.at(1) << std::endl;
}
catch(std::exception& ex)
{
    std::cout << "The following vector is out of range: " << "vec2" << std::endl;
}

Upvotes: 1

Related Questions