您目前已離線,請等候您的網際網路重新連線

HOW TO:在 Visual Basic .NET 中攔截例外狀況

本文曾發行於 CHT301283
如需本文的 Microsoft Visual C# .NET 版本,請參閱 308345

本文內容

結論
攔截及處理例外狀況是一個標準的程式設計作業。本文將告訴您,如何使用try-catch-finally區塊來攔截例外狀況。try-catch-finally區塊像是一種「包裝紙」,您可以將它置於有可能發生例外狀況的程式碼四周。

一個try-catch-finally區塊是由下列幾個區段所組成:
  • 任何可能會擲回例外狀況的程式碼都會被置於try區塊內。
  • 若已擲回例外狀況,即會進入catch區塊,則程式可以執行適當的作業來復原或警告使用者。
  • finally區塊中的程式碼一定會執行,並會在例外狀況發生之後執行清除工作。finally區塊可有可無。
回到頁首

基本需求

下面清單提列了建議使用的硬體、軟體、網路基礎架構以及所需安裝的 Service Pack:

  • Microsoft Windows 2000 Professional、Windows 2000 Server、Windows 2000 Advanced Server 或 Windows NT 4.0 Server
  • Microsoft Visual Basic .NET
回到頁首

如何在 Visual Basic .NET 中攔截例外狀況

  1. 在 Visual Basic .NET 中建立一個新的主控台應用程式。
  2. 在 Sub Main() 程序中插入以下程式碼範例。此範例宣告並初始化三個變數,但在初始化「k」子句時發生錯誤:
    ' This code generates an exception.	Console.WriteLine("We're going to divide 10 by 0 and see what happens...")	Console.WriteLine()	Dim i as Integer = 10	Dim j as Integer = 0	Dim k As Integer k = i/j ' Error on this line.
  3. 按 F5 鍵即可檢視此例外狀況。
  4. 在您的程式碼附近try-catch陳述式換行以攔截此錯誤。以下程式會攔截程式碼中擲回的所有錯誤,並顯示一個泛用的錯誤訊息。請將 Sub Main() 程序中的程式碼以下列程式碼取代:
    ' This code shows how to catch an exception.Try	Console.WriteLine("We're going to divide 10 by 0 and see what happens...")	Console.WriteLine()	Dim i as Integer = 10	Dim j as Integer = 0	Dim k As Integer k = i/j ' Error on this line. Control jumps to the catch block.Catch	Console.WriteLine("An error occurred.")End Try
  5. 按 CTRL+F5 執行此專案。請注意此處顯示了來自catch區塊的錯誤訊息。
  6. 如果無論是否有錯誤,均須完成清理或後處理的工作,請使用try-catch-finally陳述式的finally部份。無論是否發生例外狀況,陳述式中finally部份的程式碼一定會執行。即使沒有發生任何錯誤,下列程式會仍在主控台上顯示「This statement is always printed」。請以下列程式碼取代 Sub Main() 程式碼:
    ' This code shows how to catch an exception.	Try	Console.WriteLine("We're going to divide 10 by 0 and see what happens...")	Console.WriteLine()	Dim i as Integer = 10	Dim j as Integer = 0	Dim k As Integer k = i/j ' Error on this line. Control jumps to the catch block.Catch	Console.WriteLine("An error occurred.")Finally   ' This section is performed regardless of the above processing.	Console.WriteLine()	Console.WriteLine("This statement is always printed")End Try
  7. 按 CTRL+F5 執行此專案。
  8. 您可以在catch陳述式中使用例外狀況物件來擷取此例外狀況的相關細節。一個例外狀況中會有許多屬性能協助您找出與例外狀況相關的協助、來源甚至堆疊資訊。這個資訊對於追蹤例外狀況的原因,或提供其來源的較佳解釋而言,十分有用。下例範例攔截了一個例外狀況,並列出特定的錯誤訊息。同樣地,您可以用以下程式碼取代 Sub Main() 程序中的程式碼:範例 1
    ' This code shows how to catch an exception.Try	Console.WriteLine("We're going to divide 10 by 0 and see what happens...")	Console.WriteLine()	Dim i as Integer = 10	Dim j as Integer = 0	Dim k As Integer k = i/j ' Error on this line. Control jumps to the catch block.Catch e As Exception  ' Perform code that deals with the exception                      ' or informs the user what occurred.	Console.WriteLine("The following error occurred:")	Console.WriteLine(e.ToString())  ' Print the error message to the user.Finally   ' This section is performed regardless of the above processing.	Console.WriteLine()	Console.WriteLine("This statement is always printed")End Try
    範例 2
    ' This code shows how to catch an exception.Try	Console.WriteLine("We're going to divide 10 by 0 and see what happens...")	Console.WriteLine()	Dim i as Integer = 10	Dim j as Integer = 0	Dim k As Integer k = i/j ' Error on this line. Control jumps to the catch block.Catch e As Exception  ' Perform code that deals with the exception                      ' or informs the user what occurred.        Console.WriteLine("The following error occurred:")        Console.WriteLine( e.Message )     ' Print the error message.        Console.WriteLine( e.Source )      ' Name of application or object                                           ' that caused the error        Console.WriteLine( e.StackTrace )  ' String that contains the stack                                            ' trace for this exceptionFinally   ' This section is performed regardless of the above processing.        Console.WriteLine()        Console.WriteLine("This statement is always printed")End Try
  9. 到此為止,您已經處理了一個非特定例外狀況的特別案例。但若事先知道會發生哪依類型的例外狀況,便可攔截預期的例外狀況並作適當的處理。接下來您可以使用多重Catch區塊來捕捉其他例外狀況進行處理。以下即為範例:
    ' Attempt to do some file processing.' This can cause a number of potential exceptions.' Note that you can use the specific exceptions to get extra information about that exception,' but this example focuses on showing control execution for those exceptions.Try	File.Create("c:/temp/test.txt")  ' Can fail for a number of reasonsCatch ioe As System.IO.IOException ' This error may occur if the Temp folder does not exist.	Console.WriteLine("An IO error occurred. The c:\temp folder does not exist")Catch se As System.Security.SecurityException ' You do not have the appropriate permission                                              ' to take this action.	Console.WriteLine("You don't have the security permissions to take this action!")Catch e As Exception    ' Catch all other exceptions.	Console.WriteLine( e.ToString() )  ' Print the standard exception information.End Try
    由於電腦的組態可能不相同,此步驟的範例不見得會擲回例外狀況。若想強制產生 IO 例外狀況,請將檔案路徑改為您電腦上所不存在的資料夾。
回到頁首
参考
如需詳細資訊,請參閱 Microsoft .NET Framework Software Development Kit (SDK)。

回到頁首

本文件是根據 Microsoft Knowledge Base 文件編號 Q301283 翻譯的。若要參考原始英文文件內容,請至以下網址:

error handling try...catch...finally
內容

文章識別碼:301283 - 最後檢閱時間:02/15/2002 15:00:00 - 修訂: 1.0

  • Microsoft Visual Basic .NET 2002 Standard Edition
  • kbhowto kbhowtomaster KB301283
意見反應