共用方式為


例外:處理和刪除例外

下列指示和範例示範如何攔截和刪除例外狀況。 如需有關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 。 只有在catch區塊中的程式代碼拋出try語句中指定類型的例外時,才會執行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 例外狀況巨集轉換

另請參閱

例外狀況處理