Qt异常处理

/
#ifndef WIDGET_H
#define WIDGET_H

#include
#include

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);                

你可能感兴趣的:(Qt)