Qt异常处理

/
#ifndef WIDGET_H
#define WIDGET_H

#include <QtGui>
#include <QtCore>

class Widget : public QWidget
{
Q_OBJECT
private:
int a;
QLineEdit* le;
QLabel* label;
public:
Widget(QWidget *parent = 0);
~Widget();
private slots:
void compute();
private:
void check();

};

#endif // WIDGET_H
/


/

#include "widget.h"

Widget::Widget(QWidget *parent)
: QWidget(parent)
{
this->setFixedSize(400,300);          
le = new QLineEdit(this);
le->setFixedSize(150,30);
le->move(10,10);
QPushButton* btn = new QPushButton("sqrt",this);
btn->setFixedSize(50,30);
btn->move(170,10);
label = new QLabel(this);
label->setFixedSize(300,200);
label->move(10,50);
label->show();
le->show();
btn->show();
connect(btn,SIGNAL(clicked()),this,SLOT(compute()));

}

void Widget::check()
   
if(le->text()=="")
{
throw QString("Please input a positive number!");             //抛出異常信息
//        throw 1;                                                        
}
else
{
if(a<0)
{
throw QString("Do input a positive number!");                   //抛出異常信息
//            throw 2;
       
}

}
void Widget::compute()
{
try                                                         //定義異常
{
a = le->text().toInt();
check();                                                 //調用函數,確保異常被提前抛出
label->clear();
double root = sqrt(a);                            //關鍵位置,容易出錯的地方。
QString res = QString::number(root);
label->setText(res);
}
catch(QString exception)                      //定義異常處理,可以抓取多種類型的異常信息
//    catch(int errorcode)
{
QMessageBox::about(this,"Error",exception);
//        QMessageBox::about(this,"Error",QString::number(errorcode));
}
}

Widget::~Widget()
{
}

/


-------------------------------------------boundary----------------------------------------

在上面的异常处理中,我们可以看到,throw可以带参数(可以是int,也可以使QString),也可以不带参数(对应的catch(...)).

当然,一定要记住,try{}catch(){}一定要异常定义得正确,不然,都已经throw出去了,还没到catch...就会报错说:

Qt has caught an exception thrown from an event handler. Throwing
exceptions from an event handler is not supported in Qt. You must
reimplement QApplication::notify() and catch all exceptions there.

QWaitCondition: Destroyed while threads are still waiting

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值