1)例子1
try
{
int a=5/0;
}
catch(…)
{
printf(“catch the exception!”);
}
2)例子2
void Widget::check()
{
if(le->text()==””)
{
throw QString(“Please input a positive number!”);
//
}
else
{
if(a<0)
{
throw QString(“Do input a positive number!”);
//
}
}
}
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)
//
{
QMessageBox::about(this,”Error”,exception);
//
}
}
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.