共用方式為


HOW TO:明確擲回例外狀況

更新:2007 年 11 月

您可以使用 throw 陳述式,明確擲回例外狀況。您也可以使用 throw 陳述式,再次將已攔截的例外狀況擲回。加入資訊至例外狀況 (在偵錯時被重新擲回以提供更多資訊),是良好的程式設計方式。

下列程式碼範例使用 Try/Catch 區塊來攔截可能的 FileNotFoundException。Try 區塊之後的是會攔截 FileNotFoundException,且如果沒找到資料檔案就將訊息寫入至主控台的 Catch 區塊。下一個陳述式是 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();
      }
   }
}

請參閱

工作

HOW TO:使用 Try/Catch 區塊攔截例外狀況

HOW TO:使用 Catch 區塊中的特定例外狀況

HOW TO:使用 Finally 區塊

其他資源

例外處理基礎觀念