0

我想访问对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)

4

1 回答 1

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;
}
于 2013-04-28T20:17:48.577 回答