使用用户筛选的异常处理程序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. 这些处理程序使用含有关键字 WhenCatch 语句。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