在Qt中没有遇到异常

时间:2014-08-28 11:50:23

标签: c++ qt

我在Qt中遇到异常问题。

这是我的代码:

mainwindow.cpp

...
void MainWindow::on_editFanButton_clicked()
{
    Fan *fan = 0;
    try
    {
        fan = new Fan(this->selectedFanId(),this);
        connect(fan,SIGNAL(edited()),this,SLOT(fanEdited()));
        fan->edit();

    }
    catch(QString e)
    {
        delete fan;
        QMessageBox::critical(this,"Błąd",e);
    }
}
...

fan.cpp

void Fan::edit()
{
    FanEdit *fanEdit = new FanEdit(this);
    connect(fanEdit,SIGNAL(fanEdited()),this,SLOT(fanEdited()));
    fanEdit->show();
}
void Fan::fanEdited()
{
    emit edited();
}
...

fanedit.cpp

void FanEdit::on_saveButton_clicked()
{
    DatabaseConnector *databaseConnector = 0;
    databaseConnector = new DatabaseConnector();

    QSqlQuery *query = new QSqlQuery();
    if(peselChanged)
    {
        query->prepare("select * from kibic where pesel= :pesel");
        query->bindValue(":pesel",ui->peselEdit->text());
        query->exec();
        if(query->next()) throw QString("Kibic o podanym numerze pesel już istnieje!");
    }

    ...

}

我在void FanEdit::on_saveButton_clicked()中抛出异常时遇到程序终止错误。可能它会终止,因为没有发现异常。

我应该在哪里捕获异常?在mainwindow.cpp或fan.cpp中重新抛出它?

1 个答案:

答案 0 :(得分:1)

我认为FanEdit::on_saveButton_clicked()未调用MainWindow::on_editFanButton_clicked()。您必须将FanEdit::on_saveButton_clicked()包装到try-catch块中:

void FanEdit::on_saveButton_clicked()
{
    try
    {
       // code goes here
    } 
    catch (...)
    {
       // don't rethrow
    }
}

您不能重新抛出异常,因为Qt doesn't like it