Dela via


Så här utlöser du uttryckligen undantag

Du kan uttryckligen utlösa ett undantag med hjälp av C# throw eller Visual Basic-instruktionen Throw . Du kan också utlösa ett undantag som fångas igen med hjälp av -instruktionen throw . Det är bra kodningspraxis att lägga till information i ett undantag som är återväxt för att ge mer information vid felsökning.

I följande kodexempel används ett try/catch block för att fånga en möjlig .FileNotFoundException Efter blocket try finns ett catch block som fångar FileNotFoundException och skriver ett meddelande till konsolen om datafilen inte hittas. Nästa instruktion är instruktionen throw som genererar en ny FileNotFoundException och lägger till textinformation i undantaget.

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

Se även