Skip to content

Instantly share code, notes, and snippets.

@jeffhandley
Created November 3, 2011 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffhandley/1335479 to your computer and use it in GitHub Desktop.
Save jeffhandley/1335479 to your computer and use it in GitHub Desktop.
Checking for a fatal exception
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