以下说明和示例演示如何捕获和删除异常。 有关异常
异常处理程序必须删除它们处理的异常对象,因为未能删除异常会导致每当该代码捕获异常时内存泄漏。
块 catch
在以下情况下必须删除异常:
该
catch
块引发新的异常。当然,如果再次引发相同的异常,则不得删除该异常:
catch (CException* e) { if (m_bThrowExceptionAgain) throw; // Do not delete e else e->Delete(); }
执行从块内
catch
返回。
注释
删除 a CException
时,请使用 Delete
成员函数删除异常。 请勿使用 delete
关键字,因为如果异常不在堆上,它可能会失败。
捕获和删除异常
使用
try
关键字设置try
块。 执行可能在块中try
引发异常的任何程序语句。使用
catch
关键字设置catch
块。 将异常处理代码放在块中catch
。 仅当块中的catch
代码引发语句中指定的类型的异常时,才会执行块中的catch
代码try
。以下主干演示了如何
try
正常排列块catch
: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 异常宏转换。