PDA

View Full Version : How to catch out of range array crashed error?



binary001
10th October 2015, 17:44
Hi,

After I pressed pushbutton (four times) , variable i is reach 3 (a array is out of range so) application is crashed.
I don't fix this error with checking of array size. I only want to use try .. catch in sample



//header file
QString a[3];
int i;

//cpp file
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
a[0]="Zero";
a[1]="Three";
a[2]="Two";
i=0;
}

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::on_pushButton_clicked()
{
try {
ui->label->setText(a[i++]);
}
catch(std::exception &e){
qDebug() << "error1" << endl;
}
catch (...)
{
qDebug() << "error2" << endl;
}
}

ars
10th October 2015, 18:12
Your example code does not throw exceptions, it simply crashes (as you already observed). If you want to experiment with exceptions, replace your

QString a[3];
by

#include <vector>
std::vector<QString> a(3); // 3 element vector filled with QString()

Next replace the access to the array elements

ui->label->setText(a[i++]);
by

ui->label->setText(a.at(i));
Note that using operator [] of std::vector does not do any range checking, while at() method will check the range and throw exception std::out_of_range if the index is not inside the vector range. For more details see http://www.cplusplus.com/reference/vector/vector/at/.

Best regards
ars