关键异常

通常,大多数异常都不是那么重要,但是有一些非常严重的异常情况可能无法处理,例如着名的 System.StackOverflowException。但是,还有其他可能会被 Catch ex As Exception 隐藏起来,例如 System.OutOfMemoryExceptionSystem.BadImageFormatExceptionSystem.InvalidProgramException。如果你无法正确处理它们,那么将它们排除在外是一种很好的编程习惯。要过滤掉这些异常,我们需要一个帮助方法:

Public Shared Function IsCritical(ex As Exception) As Boolean
    Return TypeOf ex Is OutOfMemoryException OrElse
           TypeOf ex Is AppDomainUnloadedException OrElse
           TypeOf ex Is AccessViolationException OrElse
           TypeOf ex Is BadImageFormatException OrElse
           TypeOf ex Is CannotUnloadAppDomainException OrElse
           TypeOf ex Is ExecutionEngineException OrElse ' Obsolete one, but better to include
           TypeOf ex Is InvalidProgramException OrElse
           TypeOf ex Is System.Threading.ThreadAbortException
End Function

用法:

Try
    SomeMethod()
Catch ex As Exception When Not IsCritical(ex)
    Console.WriteLine("Exception caught: " & ex.Message)
End Try