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

文章翻譯 文章翻譯
文章編號: 301283 - 檢視此文章適用的產品。
本文曾發行於 CHT301283
全部展開 | 全部摺疊

在此頁中

結論

攔截及處理例外狀況是一個標準的程式設計作業。本文將告訴您,如何使用 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 exception
    Finally   ' 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 reasons
    
    Catch 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 翻譯的。若要參考原始英文文件內容,請至以下網址:

http://support.microsoft.com/support/kb/articles/Q301/2/83.asp

屬性

文章編號: 301283 - 上次校閱: 2002年2月15日 - 版次: 1.0
這篇文章中的資訊適用於:
  • Microsoft Visual Basic .NET 2002 Standard Edition
關鍵字:?
kbhowto kbhowtomaster KB301283
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。

提供意見

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com