如何:显式引发异常

可以使用 throw 语句显式引发异常。 还可以使用 throw 语句再次引发捕获的异常。 较好的编码做法是,向再次引发的异常添加信息以在调试时提供更多信息。

下面的代码示例使用 try/catch 块捕获可能的 FileNotFoundException。 try 块后面是 catch 块,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 块

其他资源

异常处理基础知识