在MFC中异常处理机制有两种:
- C++异常,在MFC3.0或者以后的版本才可用
- MFC异常宏,在MFC1.0或者以后的版本可用
如果你要用MFC,编写一个新应用程序,你应该使用C++异常机制,如果你现有的应用程序已近使用了MFC异常宏,你可以继续使用MFC异常宏。当然,你也可以用C++异常代替已有的MFC异常宏。
采用C++异常代替MFC异常宏优点:
- 使用C++异常,编写的代码生成的模块(EXE,DLL)更小
- C++异常关键字非常通用,它能处理任何异常类型(int,float,char 等等),而MFC异常宏仅能处理CException类和继承于CException的类
MFC异常宏和C++异常最大的区别是,当异常被捕获后,MFC异常宏会自动的delete掉捕获的异常,C++异常需要你手动的delete掉捕获的异常。
- MFC异常宏
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
- C++异常
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所写。
时间: 2024-09-27 11:30:24