1. 程式人生 > >解密MFC中異常處理

解密MFC中異常處理

在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, THROWTHROW_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所寫。