Created
November 3, 2011 01:06
-
-
Save jeffhandley/1335479 to your computer and use it in GitHub Desktop.
Checking for a fatal exception
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal static class ExceptionHandlingUtility | |
{ | |
/// <summary> | |
/// Determines if an <see cref="Exception"/> is fatal and therefore should not be handled. | |
/// </summary> | |
/// <example> | |
/// try | |
/// { | |
/// // Code that may throw | |
/// } | |
/// catch (Exception ex) | |
/// { | |
/// if (ex.IsFatal()) | |
/// { | |
/// throw; | |
/// } | |
/// | |
/// // Handle exception | |
/// } | |
/// </example> | |
/// <param name="exception">The exception to check</param> | |
/// <returns><c>true</c> if the exception is fatal, otherwise <c>false</c>.</returns> | |
public static bool IsFatal(this Exception exception) | |
{ | |
Exception outerException = null; | |
while (exception != null) | |
{ | |
if (IsFatalExceptionType(exception)) | |
{ | |
Debug.Assert(outerException == null || ((outerException is TypeInitializationException) || (outerException is TargetInvocationException)), | |
"Fatal nested exception found"); | |
return true; | |
} | |
outerException = exception; | |
exception = exception.InnerException; | |
} | |
return false; | |
} | |
private static bool IsFatalExceptionType(Exception exception) | |
{ | |
if ((exception is ThreadAbortException) || | |
((exception is OutOfMemoryException) && !(exception is InsufficientMemoryException))) | |
{ | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment