异常:捕捉和删除异常

以下说明演示如何捕捉异常和删除的示例。 有关 try的更多信息, catch和 throw 关键字,请参见 C++ 异常处理

它们处理的异常处理程序必须删除异常对象,因为异常,如果删除一导致内存泄漏,则只要该代码捕获异常。

catch 块必须删除时,通常引发异常:

  • catch 块引发一个新异常。

    当然,在中,如果您再次,引发同一异常无法删除的异常:

    catch(CException* e)
    {
       if (m_bThrowExceptionAgain)
          throw; // Do not delete e 
       else 
          e->Delete();
    }
    
  • 执行返回从 catch 块内部。

备注

删除当 CException时,请使用 删除 成员函数删除异常。不使用 删除 关键字,因为它可能失败,则异常不在堆。

捕获异常和删除

  • 使用 try 关键字来设置 try 块。 练习可能引发在 try 块内的异常的程序语句。

    使用 catch 关键字来设置 catch 块。 放置异常处理代码。catch 块。 在 try 块内的代码引发 catch 语句中,指定类型的异常。catch 块中的代码。

    下面的主干显示通常如何具有 trycatch 块:

    try
    {
       // Execute some code that might throw an exception.
       AfxThrowUserException();
    }
    catch( CException* e )
    {
       // Handle the exception here. 
       // "e" contains information about the exception.
       e->Delete();
    }
    

    引发异常时,控制将传递到异常匹配声明异常类型的第一 catch 块。 您可以选择性地处理异常的不同类型的运行 catch 块中。如下所示:

    try
    {
       // Execute some code that might throw an exception.
       AfxThrowUserException();
    }
    catch( CMemoryException* e )
    {
       // Handle the out-of-memory exception here.
       e->Delete();
    }
    catch( CFileException* e )
    {
       // Handle the file exceptions here.
       e->Delete();
    }
    catch( CException* e )
    {
       // Handle all other types of exceptions here.
       e->Delete();
    }
    

有关更多信息,请参见 异常:从 MFC 宏转换异常

请参见

概念

MFC 中的异常处理