异常:捕捉和删除异常

下列说明和示例演示如何捕获和删除异常。 有关 trycatchthrow 关键字的详细信息,请参阅异常和错误处理的新式 C++ 最佳做法

你的异常处理程序必须删除其处理的异常对象,因为如果未删除异常将导致在代码捕获异常时出现内存泄漏。

出现下列情况时,catch 块必须删除异常:

  • catch 块将引发一个新异常。

    当然,如果您再次引发同一异常,则不得删除此异常:

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

注意

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

捕获和删除异常

  1. 使用 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 异常宏转换

另请参阅

异常处理