分享方式:


如何明確擲回例外狀況

您可以使用 C# throw 或 Visual Basic Throw 陳述式明確地擲回例外狀況。 您也可以使用 throw 陳述式,再次擲回所攔截的例外狀況。 建議您撰寫程式碼,將資訊加入要重新擲回的例外狀況,以在偵錯時提供更多資訊。

下列程式碼範例使用 try/catch 區塊來攔截可能的 FileNotFoundExceptiontry 區塊後面會接著 catch 區塊,該區塊可在找不到資料檔案時攔截 FileNotFoundException,並將訊息寫入主控台。 下一個陳述式是 throw 陳述式,會擲回新的 FileNotFoundException ,並將文字資訊新增到例外狀況。

var fs = default(FileStream);
try
{
    // Open a text tile.
    fs = new FileStream(@"C:\temp\data.txt", FileMode.Open);
    var sr = new StreamReader(fs);

    // Read a value from the file and output to the console.
    string? line = sr.ReadLine();
    Console.WriteLine(line);
}
catch (FileNotFoundException e)
{
    Console.WriteLine($"[Data File Missing] {e}");
    throw new FileNotFoundException(@"[data.txt not in c:\temp directory]", e);
}
finally
{
    fs?.Close();
}
Option Strict On

Imports System.IO

Public Class ProcessFile

    Public Shared Sub Main()
        Dim fs As FileStream = Nothing
        Try
            ' Opens a text file.
            fs = New FileStream("c:\temp\data.txt", FileMode.Open)
            Dim sr As New StreamReader(fs)

            ' A value is read from the file and output to the console.
            Dim line As String = sr.ReadLine()
            Console.WriteLine(line)
        Catch e As FileNotFoundException
            Console.WriteLine($"[Data File Missing] {e}")
            Throw New FileNotFoundException("[data.txt not in c:\temp directory]", e)
        Finally
            If fs IsNot Nothing Then fs.Close()
        End Try
    End Sub
End Class

另請參閱