Share via


HOW TO:使用 Try/Catch 區塊攔截例外狀況

放置可能擲回例外狀況的程式碼區段於 Try 區塊中,並放置處理例外狀況的程式碼於 Catch 區塊中。 Catch 區塊為一系列的陳述式,以關鍵字 catch 開始,其後接著例外狀況類型和要採取的動作。

注意事項注意事項

幾乎任何一行程式碼都可以造成例外狀況,尤其是 Common Language Runtime 本身擲回的例外狀況,例如 OutOfMemoryExceptionStackOverflowException。大部分應用程式都不必處理這些例外狀況,但在撰寫要被他人使用的程式庫時,您應該留意這個可能性。如需何時要在 Try 區塊中設定程式碼的詳細資訊,請參閱處理例外狀況的最佳作法

下列程式碼範例使用 Try/Catch 區塊來攔截可能的例外狀況。 Main 方法包含 Try 區塊,區塊具有會開啟名稱為 data.txt 的資料檔並從檔案寫入字串的 StreamReader 陳述式。 接在 Try 區塊之後的是攔截任何從 Try 區塊產生的例外狀況的 Catch 區塊。

範例

Imports System
Imports System.IO

Public Class ProcessFile
    Public Shared Sub Main()
        Try
            Dim sr As StreamReader = File.OpenText("data.txt")
            Console.WriteLine("The first line of this file is {0}", sr.ReadLine())
        sr.Close()
        Catch e As Exception
            Console.WriteLine("An error occurred: '{0}'", e)
        End Try
    End Sub
End Class
using System;
using System.IO;

public class ProcessFile
{
    public static void Main()
    {
        try
        {
            StreamReader sr = File.OpenText("data.txt");
            Console.WriteLine("The first line of this file is {0}", sr.ReadLine());
        sr.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: '{0}'", e);
        }
    }
}
using namespace System;
using namespace System::IO;

public ref class ProcessFile
{
public:
    static void Main()
    {
        try
        {
            StreamReader^ sr = File::OpenText("data.txt");
            Console::WriteLine("The first line of this file is {0}", sr->ReadLine());
        sr->Close();
        }
        catch (Exception^ e)
        {
            Console::WriteLine("An error occurred: '{0}'", e);
        }
    }
};

int main()
{
    ProcessFile::Main();
}

這個範例說明要攔截所有例外狀況的基本 Catch 陳述式。 通常,不使用基本的 Catch 陳述式來攔截特定類型的例外狀況是一種十分不錯的程式設計作法。 如需攔截特定例外狀況的詳細資訊,請參閱使用 Catch 區塊中的特定例外狀況

請參閱

工作

HOW TO:使用 Catch 區塊中的特定例外狀況

HOW TO:明確擲回例外狀況

HOW TO:建立使用者定義的例外狀況

HOW TO:使用 Finally 區塊

其他資源

例外處理基礎觀念