HOW TO:在 Visual Basic 中使用 Try…Finally 區塊清除資源

Try 區塊中的 Finally 陳述式可用來確定所配置的資源都已清除。 Finally 區塊中之程式碼的執行時機是在例外處理 (Exception Handling) 程式碼之後,而在控制項回到呼叫程序之前。 即使程式碼擲出例外狀況 (Exception),且即使已在 Catch 區塊中加入明確的 Exit Function (或 Exit Sub) 陳述式,仍會執行 Finally 區塊中的程式碼。

如果不需要攔截特定例外狀況,則 Using 陳述式的行為會像 Try…Finally 區塊,且不論是以何種方式結束該區塊,都保證會處置 (Dispose) 資源。 即使在未處理例外狀況的情況下也是一樣。 如需詳細資訊,請參閱 Using 陳述式 (Visual Basic)

若要使用 Finally 陳述式清除資源

  • 將想要執行的程式碼 (不論例外狀況為何) 放入 Finally 區塊中。 下列程式碼會建立 StreamReader,並使用它來讀取檔案。

    Dim reader As New System.IO.StreamReader("C:\testfile")
    Try
        reader.ReadToEnd()
    Catch ex As System.IO.IOException
        MsgBox("Could not read file")
    Finally
        'This command is executed whether or not the file can be read
        reader.Close()
    End Try
    

請參閱

工作

HOW TO:在 Visual Basic 中使用 Try…Catch 區塊測試程式碼

HOW TO:檢查例外狀況的內部例外狀況 (Visual Basic)

HOW TO:處置系統資源 (Visual Basic)

參考

Using 陳述式 (Visual Basic)

其他資源

例外處理工作 (Visual Basic)