使用使用者篩選的例外狀況處理常式Using User-Filtered Exception Handlers

目前,Visual Basic 支援使用者篩選的例外狀況。Currently, Visual Basic supports user-filtered exceptions. 使用者篩選例外狀況處理常式會依據您定義的例外狀況需求,攔截和處理例外狀況。User-filtered exception handlers catch and handle exceptions based on requirements you define for the exception. 這些處理常式會使用 Catch 陳述式搭配 When 關鍵字。These handlers use the Catch statement with the When keyword.

當特定例外狀況物件對應至多個錯誤時,這個技術非常有用。This technique is useful when a particular exception object corresponds to multiple errors. 在此情況下,物件通常會有一個屬性,其中包含與錯誤相關聯的特定錯誤碼。In this case, the object typically has a property that contains the specific error code associated with the error. 您可以在運算式中使用錯誤碼屬性,只選取您想要在該 Catch子句中處理的特定錯誤。You can use the error code property in the expression to select only the particular error you want to handle in that Catch clause.

下列 Visual Basic 範例示範 Catch/When陳述式。The following Visual Basic example illustrates the Catch/When statement.

Try  
    'Try statements.  
    Catch When Err = VBErr_ClassLoadException
    'Catch statements.
End Try  

不會以任何方式限制使用者篩選子句的運算式。The expression of the user-filtered clause is not restricted in any way. 如果在使用者篩選運算式執行期間發生例外狀況,會捨棄該例外狀況,且篩選運算式會被視為必須評估為 false。If an exception occurs during execution of the user-filtered expression, that exception is discarded and the filter expression is considered to have evaluated to false. 在此情況下,通用語言執行平台會繼續搜尋目前例外狀況的處理常式。In this case, the common language runtime continues the search for a handler for the current exception.

結合特定例外狀況和使用者篩選的子句Combining the Specific Exception and the User-Filtered Clauses

Catch 陳述式可以包含特定例外狀況和使用者篩選的子句。A catch statement can contain both the specific exception and the user-filtered clauses. 執行階段會先測試特定例外狀況。The runtime tests the specific exception first. 如果特定例外狀況成功,則執行階段會執行使用者篩選。If the specific exception succeeds, the runtime executes the user filter. 一般篩選可以包含類別篩選中所宣告之變數的參考。The generic filter can contain a reference to the variable declared in the class filter. 請注意,無法反轉兩個篩選子句的順序。Note that the order of the two filter clauses cannot be reversed.

下列 Visual Basic 範例會顯示 Catch 陳述式中的特定例外狀況 ClassLoadException,以及使用 When 關鍵字的使用者篩選子句。The following Visual Basic example shows the specific exception ClassLoadException in the Catch statement as well as the user-filtered clause using the When keyword.

Try  
    'Try statements.
    Catch cle As ClassLoadException When cle.IsRecoverable()  
    'Catch statements.
End Try  

另請參閱See also