2

如何在 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 用作经验丰富的设计师。所以我会尝试捕捉并记录错误,这样他们的自动化测试脚本就不会崩溃并且很容易找出错误点。——昨日中柱

4

2 回答 2

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...";
    }
}
于 2013-07-08T03:59:22.423 回答
0

Check number of records yourself

QList<int> list;
for(int i=0; i<list.size(); i++)
    qDebug() << list.at(i);

or use the QListIterator

QList<int> list;
QListIterator<int> iterator;
while(iterator.hasNext())
    qDebug() << iterator.next();
于 2013-07-08T06:05:03.247 回答