How to catch out of range array crashed error?
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
Code:
//header file
int i;
//cpp file
MainWindow
::MainWindow(QWidget *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;
}
}
Re: How to catch out of range array crashed error?
Your example code does not throw exceptions, it simply crashes (as you already observed). If you want to experiment with exceptions, replace your
by
Code:
#include <vector>
std::vector<QString> a(3); // 3 element vector filled with QString()
Next replace the access to the array elements
Code:
ui->label->setText(a[i++]);
by
Code:
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