在MFC中异常处理机制有两种:
如果你要用MFC,编写一个新应用程序,你应该使用C++异常机制,如果你现有的应用程序已近使用了MFC异常宏,你可以继续使用MFC异常宏。当然,你也可以用C++异常代替已有的MFC异常宏。
采用C++异常代替MFC异常宏优点:
MFC异常宏和C++异常最大的区别是,当异常被捕获后,MFC异常宏会自动的delete掉捕获的异常,C++异常需要你手动的delete掉捕获的异常。
TRY { // Execute some code that might throw an exception. AfxThrowUserException(); } CATCH( CException, e) { // Handle the exception here. if (m_bThrowExceptionAgain) THROW_LAST(); // 没必要删除e. } END_CATCH
try { // Execute some code that might throw an exception. AfxThrowUserException(); } catch( CException* e ) { // Handle the exception here. // "e" contains information about the exception. if (m_bThrowExceptionAgain) throw; // Do not delete e else e->Delete();//删除e,否侧引起内存泄露 }
MFC异常宏,TRY, CATCH, AND_CATCH, END_CATCH, THROW,THROW_LAST;C++异常关键字,try,catch,throw;用C++异常代替MFC异常宏,两者之间的替换如下:
TRY (Replace it with try)
CATCH (Replace it with catch)
AND_CATCH (Replace it with catch)
END_CATCH (Delete it)
THROW (Replace it with throw)
THROW_LAST (Replace it with throw)
P.S以上内容是参考MSDN2008所写。
原文地址:http://blog.csdn.net/chen_jint/article/details/41576949