Visual Basic .NET Language Critical Exceptions


Example

Generally most of the exceptions are not that critical, but there are some really serious exceptions that you might not be capable to handle, such as the famous System.StackOverflowException. However, there are others that might get hidden by Catch ex As Exception, such as System.OutOfMemoryException, System.BadImageFormatException and System.InvalidProgramException. It is a good programming practice to leave these out if you cannot correctly handle them. To filter out these exceptions, we need a helper method:

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

Usage:

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