catch雖然區塊的自變數幾乎可以是任何數據類型,但 MFC 函式會擲回衍生自 類別CException的類型例外狀況。 若要攔截 MFC 函式擲回的例外狀況,您可以撰寫區塊 catch ,其自變數是物件的指標 CException (或衍生自 CException的物件,例如 CMemoryException)。 根據例外狀況的確切類型,您可以檢查例外狀況對象的數據成員,以收集例外狀況特定原因的相關信息。
例如,此 CFileException 類型具有 m_cause 數據成員,其中包含指定檔案例外狀況原因的列舉型別。 可能傳回值的一些範例為 CFileException::fileNotFound 和 CFileException::readOnly。
以下範例示範如何檢查CFileException的內容。 其他例外狀況類型可以類似地檢查。
try
{
CFile file(_T("\\this_file_should_not_exist.dat"), CFile::modeRead);
}
catch (CFileException* theException)
{
if (theException->m_cause == CFileException::fileNotFound)
TRACE("File not found\n");
theException->Delete();
}