哪个向量使索引超出范围异常?

时间:2013-04-28 19:58:11

标签: c++ exception-handling indexoutofboundsexception

我想访问引发超出范围异常的std::vector的引用,或者至少引发抛出异常的行号(类似于Java的堆栈跟踪)。这是一个示例程序:

#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;
}

我知道这个例子很简单,但我希望它能说明我正在寻找的功能。

编辑:实施,来自g ++ --version:g ++(GCC)4.1.2 20071124(Red Hat 4.1.2-42)

1 个答案:

答案 0 :(得分:1)

您需要自己动手:

#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;
}