例外を明示的にスローする方法

明示的に例外をスローするには、C# の throw または Visual Basic の Throw ステートメントを使用します。 throw ステートメントを使って、キャッチした例外をもう一度スローすることもできます。 再スローされる例外に情報を追加して、デバッグ時により多くの情報を提供するコーディング手法をお勧めします。

次のコード例では、try/catch ブロックを使用して可能性のある FileNotFoundException をキャッチします。 次の try ブロックは、FileNotFoundException をキャッチし、データ ファイルが見つからない場合に、メッセージをコンソールに出力する catch ブロックです。 次のステートメントは、新しい FileNotFoundException をスローして、テキスト情報を例外に追加する 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

関連項目