共用方式為


CATCH

會攔截前述擲回的第一個例外狀況類型的程式碼區塊會定義區塊。

CATCH(exception_class, exception_object_pointer_name )

參數

  • exception_class
    指定用來測試例外狀況型別。 如需標準的例外狀況類別的清單,請參閱類別用 CException

  • exception_object_pointer_name
    指定例外狀況物件的指標,這將會建立巨集的名稱。 您可用來存取內的例外狀況物件指標名稱攔截區塊。 針對您宣告了這個變數。

備註

例外狀況的處理程式碼可以質詢的例外狀況物件,如果適當的話,以取得例外狀況的詳細原因的詳細資訊。 叫用THROW_LAST巨集,以移至下一個外部例外框架的處理。 結束區塊END_CATCH巨集。

如果 exception_class 是類別CException,然後將攔截所有例外狀況型別。 您可以使用 CObject::IsKindOf 成員函式,以判斷哪一個特定的例外狀況已擲回。 若要攔截的例外狀況的幾種更好的方法是使用循序AND_CATCH陳述式,各有不同的例外狀況型別。

巨集來建立例外狀況的物件指標。 您不需要宣告它。

注意事項注意事項

攔截區塊會定義為區隔所括住的 C++ 範圍。如果您宣告變數,在此範圍內,則是只能在該範圍內,您可以存取。這也適用於 exception_object_pointer_name

如需有關例外狀況和攔截 巨集],請參閱文件 的例外狀況

範例

CFile* pFile = NULL;
// Constructing a CFile object with this override may throw
// a CFile exception and won't throw any other exceptions.
// Calling CString::Format() may throw a CMemoryException,
// so we have a catch block for such exceptions, too. Any
// other exception types this function throws will be
// routed to the calling function.
TRY
{
   pFile = new CFile(_T( "C:\\WINDOWS\\SYSTEM.INI"), 
      CFile::modeRead | CFile::shareDenyNone);
   ULONGLONG dwLength = pFile->GetLength();
   CString str;
   str.Format(_T("Your SYSTEM.INI file is %I64u bytes long.") , dwLength);
   AfxMessageBox(str);
}
CATCH(CFileException, pEx)
{
   // Simply show an error message to the user.
   pEx->ReportError();
}
AND_CATCH(CMemoryException, pEx)
{
   // We can't recover from this memory exception, so we'll
   // just terminate the app without any cleanup. Normally, 
   // an application should do everything it possibly can to
   // clean up properly and not call AfxAbort().
   AfxAbort();
}
END_CATCH
// If an exception occurs in the CFile constructor,
// the language will free the memory allocated by new
// and will not complete the assignment to pFile.
// Thus, our cleanup code needs to test for NULL.
if (pFile != NULL)
{
   pFile->Close();
   delete pFile;
}

需求

標頭: afx.h

請參閱

參考

TRY

AND_CATCH

END_CATCH

THROW (MFC)

THROW_LAST

CATCH_ALL

CException 類別

概念

MFC 巨集和全域變數