1、看看Qt源碼中如何定義QT_TRY和QT_CATCH的:
inline void qt_noop(void) {}
/* These wrap try/catch so we can switch off exceptions later.
Beware - do not use more than one QT_CATCH per QT_TRY, and do not use
the exception instance in the catch block.
If you can't live with those constraints, don't use these macros.
Use the QT_NO_EXCEPTIONS macro to protect your code instead.
*/
#ifdef QT_BOOTSTRAPPED
# define QT_NO_EXCEPTIONS
#endif
#if !defined(QT_NO_EXCEPTIONS) && defined(Q_CC_GNU) && !defined (__EXCEPTIONS) && !defined(Q_MOC_RUN)
# define QT_NO_EXCEPTIONS
#endif
#ifdef QT_NO_EXCEPTIONS
# define QT_TRY if (true)
# define QT_CATCH(A) else
# define QT_THROW(A) qt_noop()
# define QT_RETHROW qt_noop()
#else
# define QT_TRY try
# define QT_CATCH(A) catch (A)
# define QT_THROW(A) throw A
# define QT_RETHROW throw
#endif
2、我們來使用下QT的異常處理
// 在.pro 中增加如下配置 ==》 Qt默認是不開啓異常的
CONFIG += exceptions
// main.cpp
enum Except{ EXCEP_ZERO,EXCEP_ONE};
void func(int a){
if(a ==0) throw (EXCEP_ZERO); // 拋出異常
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QT_TRY {
func(1);
} QT_CATCH(Except ex) {
if(ex == EXCEP_ZERO) QT_RETHROW;
}
Widget w;
w.show();
return a.exec();
}