【发布时间】:2013-04-22 10:38:27
【问题描述】:
我想访问对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)
【问题讨论】:
-
C++ 中没有内置这样的东西,也许你的实现有一些东西,但是因为我们不知道......
-
使用两个 try-catch 语句,每次访问一次。
-
行号不会给你任何东西 - 它会在向量的 STL 标头中...首先,你可以使用两个
try/catch块。 -
与 Java 不同,C++ 不会在您的应用程序中构建调试器。如果需要堆栈跟踪,请在调试器中运行程序。
标签: c++ exception-handling indexoutofboundsexception