共用方式為


攔截 Visual C++中的例外狀況

本文說明如何使用 try-catch-finally 區塊來攔截例外狀況。

原始產品版本: Visual C++
原始 KB 編號: 815662

摘要

try-catch-finally區塊是一個包裝函式,您放在任何可能發生例外狀況的程序代碼中。 攔截和處理例外狀況是標準程序設計工作。

try-catch-finally區塊是由下列各節所組成:

  • 任何可能擲回例外狀況的程式代碼都會放在 try 區塊內。
  • 如果擲回例外狀況,則會 catch 輸入 區塊,而且程式可以執行適當的作業來復原或警示使用者。
  • 區塊中的 finally 程序代碼一律會執行,而且可以在發生例外狀況之後進行清除。 區塊是選擇性的 finally

本文參考下列Microsoft .NET Framework 類別庫命名空間: System.IOSystem.Security

在 Visual C++ .NET 中攔截例外狀況

  1. 啟動 Visual Studio .NET。

  2. [檔案] 功能表上,指向 [開新檔案] ,然後按一下 [專案]

  3. 在 Visual C++ 中,按兩下 [項目類型] 下的 [Visual C++],然後按兩下 [範本] 下的 [CLR 控制台應用程式]。

  4. 在 [ 名稱] 方塊中,輸入 Q815662,然後按兩下 [ 確定]。

  5. 使用下列程式代碼取代Q815662.cpp程式代碼視窗中的所有程序代碼。 程序代碼會宣告並初始化三個變數。 k初始化會造成錯誤。

    #include "stdafx.h"
    #using <mscorlib.dll>
    #include <tchar.h>
    using namespace System;
    void _tmain(void)
    {
        Console::WriteLine("We're going to divide 10 by 0 and see what happens...");
        Console::WriteLine();
        int i = 10;
        int j = 0;
        int k = i/j; //Error on this line.
    }
    
  6. 請按 F5。 您會收到 System.DivideByZeroException 例外狀況。

  7. try-catch在程式代碼周圍包裝 語句,以擷取錯誤。 下列程式代碼會攔截程式代碼中擲回的所有錯誤,並顯示一般錯誤訊息。 使用下列程式代碼取代Q815662.cpp程式代碼視窗中的程式代碼:

    #include "stdafx.h"
    #using <mscorlib.dll>
    #include <tchar.h>
    using namespace System;
    void _tmain(void)
    {
        try
        {
            Console::WriteLine("We're going to divide 10 by 0 and see what happens...");
            Console::WriteLine();
            int i = 10;
            int j = 0;
            int k = i/j; //Error on this line.
        }
        catch(...)
        {
            Console::WriteLine("An error occurred.");
        }
    }
    
  8. 按 CTRL+F5 執行應用程式。

    注意

    區塊的錯誤 catch 訊息會顯示,而不是系統例外狀況錯誤訊息。

  9. 如果您必須進行清除或後續處理,不論發生錯誤,請使用 __finally 語句的 try-catch-finally 一部分。 不論例外狀況為何,語句最後部分的程序代碼一律會執行。 下列程式代碼會在控制台中顯示下列訊息,即使未發生錯誤也一樣:

    This statement is always printed.  
    

    使用下列程式代碼取代Q815662.cpp程式代碼視窗中的程式代碼:

    #include "stdafx.h"
    #using <mscorlib.dll>
    #include <tchar.h>
    using namespace System;
    void _tmain(void)
    {
        try
        {
            Console::WriteLine("We're going to divide 10 by 0 and see what happens...");
            Console::WriteLine();
            int i = 10;
            int j = 0;
            int k = i/j; //Error on this line.
        }
        catch(...)
        {
            Console::WriteLine("An error occurred.");
        }
        __finally //This section is performed regardless of the above processing.
        {
            Console::WriteLine();
            Console::WriteLine("This statement is always printed");
        }
    }
    
  10. 按 CTRL+F5 執行專案。

  11. 您可以使用 exception 物件搭配 catch 語句來擷取例外狀況的詳細數據。 例外狀況物件有數個屬性,可協助您識別來源,並具有例外狀況的堆棧資訊。 這項資訊有助於追蹤例外狀況的原始原因,或提供其來源的較佳說明。 下列範例會擷取例外狀況,並提供特定的錯誤訊息。 使用下列程式代碼取代Q815662.cpp程式代碼視窗中的程式代碼:

    #include "stdafx.h"
    #using <mscorlib.dll>
    #include <tchar.h>
    using namespace System;
    using namespace System::Reflection;
    void _tmain(void)
    {
        try
        {
            Console::WriteLine("We're going to divide 10 by 0 and see what happens...");
            Console::WriteLine();
            int i = 10;
            int j = 0;
            int k = i/j; //Error on this line.
        }
        catch(Exception *e)
        {
            Console::WriteLine("An error occurred.");
            Console::WriteLine(e->Message); // Print the error message.
            Console::WriteLine(e->StackTrace); //String that contains the stack trace for this exception.
        }
        __finally //This section is performed regardless of the above processing.
        {
            Console::WriteLine();
            Console::WriteLine("This statement is always printed");
        }
        Console::ReadLine();
    }
    
  12. 在這一點之前,您已處理非特定例外狀況。 不過,如果您事先知道會發生何種例外狀況,您可以攔截預期的例外狀況,並據以處理。 使用下列程式代碼中所述的多個 catch 區塊來擷取所有其他例外狀況並加以處理:

    #include "stdafx.h"
    #using <mscorlib.dll>
    #include <tchar.h>
    using namespace System;
    using namespace System::IO;
    using namespace System::Security;
    void _tmain(void)
    {
        try
        {
            File::Create("c:\\temp\\testapp.txt"); //Can fail for a number of resons
        }
        // This error may occur if the temp folder does not exist.
        catch(IOException *ioe)
        {
            Console::WriteLine("An IOException exception occurred!");
            Console::WriteLine(ioe->ToString());
        }
        // You do not have the appropriate permission to take this action.
        catch(SecurityException *se)
        {
            Console::WriteLine("An SecurityException exception occur")
        }
        // Catch all exceptions
        catch(Exception *e)
        {
            Console::WriteLine(e->ToString());
        }
    }
    

    因為計算機設定可能不同,因此此步驟中的範例可能會或可能不會擲回例外狀況。 如果您想要強制輸入/輸出 (IO) 例外狀況,請將檔案路徑變更為計算機上不存在的資料夾。