Share via


Kivételek explicit kizárása

A C# throw vagy a Visual Basic Throw utasítás használatával explicit módon kivételt adhat ki. A kapott kivételt az utasítással throw is újra elvetheti. Jó kódolási gyakorlat, ha olyan kivételhez ad hozzá információt, amely újra létrejön, hogy a hibakeresés során további információt nyújtson.

Az alábbi példakód egy blokkot használ egy try/catch lehetséges FileNotFoundExceptionkód elfogásához. A try blokkot követve a catch blokk elfogja a FileNotFoundException fájlt, és üzenetet ír a konzolra, ha az adatfájl nem található. A következő utasítás az az throw utasítás, amely újat FileNotFoundException hoz létre, és szöveges információkat ad hozzá a kivételhez.

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

Lásd még