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

例外を明示的にスローするには、throw ステートメントを使用します。 キャッチした例外を再びスローするときにも、throw ステートメントを使用します。 実際のコードでは、デバッグ時に詳細情報を提供するために、再スローする例外に情報を追加すると便利です。

try ブロックと catch ブロックを使用して、発生する可能性のある FileNotFoundException をキャッチするコード例を次に示します。 try ブロックの後に続く catch ブロックは、データ ファイルが見つからない場合に FileNotFoundException をキャッチして、メッセージをコンソールに出力します。 その後の throw ステートメントでは、新しい FileNotFoundException をスローし、この例外にテキスト情報を追加します。

使用例

Option Strict On

Imports System
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)
          Dim line As String

          'A value is read from the file and output to the console.
          line = sr.ReadLine()
          Console.WriteLine(line)
      Catch e As FileNotFoundException
          Console.WriteLine("[Data File Missing] {0}", 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 
using System;
using System.IO;

public class ProcessFile
{
   public static void Main()
      {
      FileStream fs = null;
      try   
      {
         //Opens a text tile.
         fs = new FileStream(@"C:\temp\data.txt", FileMode.Open);
         StreamReader sr = new StreamReader(fs);
         string line;

         //A value is read from the file and output to the console.
         line = sr.ReadLine();
         Console.WriteLine(line);
      }
      catch(FileNotFoundException e)
      {
         Console.WriteLine("[Data File Missing] {0}", e);
         throw new FileNotFoundException(@"[data.txt not in c:\temp directory]",e);
      }
      finally
      {
         if (fs != null) 
            fs.Close();
      }
   }
}

参照

処理手順

方法 : Try ブロックと Catch ブロックを使用して例外をキャッチする

方法 : catch ブロックで特定の例外を使用する

方法 : finally ブロックを使用する

その他の技術情報

例外処理の基本事項