CATCH

定义捕获前面的 TRY 块引发的第一种异常类型的代码块。

CATCH(exception_class, exception_object_pointer_name )

参数

  • 异常类
    指定要测试的异常类型。 有关标准异常类列表,请参阅类 CException

  • exception_object_pointer_name
    为由宏创建的异常对象的指针指定名称。 可以使用指针名访问在 CATCH 块中的异常对象。 声明变量。

备注

如果适当,异常处理代码可以询问异常对象获取有关异常的特定原因的更多信息。 调用 THROW_LAST 宏移动处理程序到下一个外部帧。 使用 END_CATCH 宏关闭 TRY 块。

如果 exception_class 是类 CException,则将捕获所有异常类型。 可以使用 CObject::IsKindOf 成员函数确定特定的引发异常。 一种更好的方式捕获一些异常是对每个不同的异常类型使用连续的 AND_CATCH 语句。

由宏创建异常对象指针。 不需要自己声明。

备注

CATCH 块定义为大括号描述 C ++ 范围。如果在此范围声明变量,则只能在该范围中访问。这也适用于 exception_object_pointer_name

有关异常和 CATCH 宏的详细信息,请参阅文章 异常

示例

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;
}

要求

Header: afx.h

请参见

参考

TRY

AND_CATCH

END_CATCH

THROW (MFC)

THROW_LAST

CATCH_ALL

CException 类

概念

MFC 宏和全局函数