關鍵異常
通常,大多數異常都不是那麼重要,但是有一些非常嚴重的異常情況可能無法處理,例如著名的 System.StackOverflowException
。但是,還有其他可能會被 Catch ex As Exception
隱藏起來,例如 System.OutOfMemoryException
,System.BadImageFormatException
和 System.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