명시적으로 예외를 throw하는 방법

C# throw 또는 Visual Basic Throw 문을 사용하여 명시적으로 예외를 throw할 수 있습니다. throw 문을 사용하여 catch된 예외를 다시 throw할 수도 있습니다. 디버깅할 때 더 많은 정보를 제공하기 위해 다시 throw되는 예외에 정보를 추가하는 것이 좋은 코딩 습관입니다.

다음 코드 예제에서는 try/catch 블록을 사용하여 가능한 FileNotFoundException을 catch합니다. try 블록 뒤에는 FileNotFoundException을 catch하고 데이터 파일을 찾을 수 없는 경우 콘솔에 메시지를 쓰는 catch 블록이 있습니다. 다음 문은 새 FileNotFoundException을 throw하고 예외에 텍스트 정보를 추가하는 throw 문입니다.

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

참고 항목