如何在Qt中捕获“索引超出范围”异常?我使用了try / catch,但看起来它不起作用。
try {
QStringList list;
QString str = list[1];
} catch (...) {
qDebug()<<"error";
}
在Windows XP中,我可以看到下面的对话框弹出:
---------------------------
K.exe - Application Error
---------------------------
The instruction at "0x0040144c" referenced memory at "0x00040012". The memory could not be "written".
Click on OK to terminate the program
Click on CANCEL to debug the program
---------------------------
OK Cancel
---------------------------
这就是我需要这样做的原因。我们的一些经验不足的工程师需要使用Qt C ++语言的一小部分来进行一些自动化测试工作。我们不能强迫他们使用QList作为一个经验丰富的设计师。因此,我将尝试捕获并记录错误,以便他们的自动化测试脚本不会崩溃并且很容易找出错误点。 - 昨天中柱
答案 0 :(得分:1)
正如评论者指出的那样,你不能。
虽然Qt支持异常,但它不使用它们。有人在qt-project的论坛上建议增加可移植性(因为有些平台不支持异常处理)。
另一种方法是在尝试访问它们之前自己检查值,或者为需要异常处理的类构建自己的包装器。
说明差异的一个例子:
#include <QCoreApplication>
#include <QString>
#include <QDebug>
#include <QStringList>
#include <vector>
void t1()
{
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(4);
qDebug() << "Val: " << vec.at(3);
}
void t2()
{
QStringList sl;
sl << "Foo" << "Bar" << "Herp" << "Derp";
qDebug() << sl.at(0);
qDebug() << sl.at(5);
}
void t3()
{
qDebug() << "Going down!";
abort();
}
int main()
{
try {
t1();
//t2();
//t3();
} catch (...) {
qDebug() << "Close one...";
}
}
答案 1 :(得分:0)
自己检查记录数
QList<int> list;
for(int i=0; i<list.size(); i++)
qDebug() << list.at(i);
或使用QListIterator
QList<int> list;
QListIterator<int> iterator;
while(iterator.hasNext())
qDebug() << iterator.next();