I <3 Steve McConnell*
Coding Horror
programming and human factors
by Jeff Atwood

October 26, 2004

Creating Even More Exceptional Exceptions

In response to a previous post decrying the lack of a master list of Exception classes for .NET, a helpful reader pointed out a clever little utility buried in the .NET SDK:

Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin\wincv.exe

Wincv works well, but it doesn't allow me to sort or even copy out the class names. After reflecting on this a bit, I generated the following console app:

    Sub Main()
        ReflectionSearch(".*exception$")
        Console.ReadLine()
    End Sub

    Sub ReflectionSearch(ByVal strPattern As String)
        Dim a As Reflection.Assembly
        Dim m As Reflection.Module
        Dim t As Type
        Dim al As New ArrayList
        Dim sl As New SortedList
        Dim strAssemblyName As String

        For Each strAssemblyName In DefaultAssemblyList()
            a = Reflection.Assembly.Load(strAssemblyName)
            For Each m In a.GetModules
                For Each t In m.GetTypes
                    al.Add(t)
                    Dim strFullName As String = t.FullName
                    If Regex.IsMatch(strFullName, strPattern, RegexOptions.IgnoreCase) Then
                        sl.Add(strFullName, Nothing)
                    End If
                Next
            Next
        Next

        Dim de As DictionaryEntry
        For Each de In sl
            Console.WriteLine(de.Key)
        Next
        Console.WriteLine(sl.Count.ToString & " matches for " & strPattern)
    End Sub

    Function DefaultAssemblyList() as ArrayList
        Dim al As New ArrayList
        With al
            .Add("mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            .Add("System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            .Add("System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            .Add("System.Runtime.Remoting, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            .Add("System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            .Add("System.Xml, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
            .Add("System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
            .Add("System.DirectoryServices, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
            .Add("System.Drawing.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
            .Add("System.Drawing, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
            .Add("System.Messaging, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
            .Add("System.Runtime.Serialization.Formatters.Soap, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
            .Add("System.Security, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
            .Add("System.ServiceProcess, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
            .Add("System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
            .Add("System.Web.Services, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
            .Add("System.Management, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
        End With
        Return al
    End Function

This console app produces the following (mostly) sorted list of 141 classes in the framework that end in Exception. Now there's really no reason to throw generic System.Exception, because one of these likely to be a better match-- or, failing that, a custom Exception. Thanks for the tips, guys.

p.s. I really am lazy.

System.AppDomainUnloadedException
System.ApplicationException
System.ArgumentException
System.ArgumentNullException
System.ArgumentOutOfRangeException
System.ArithmeticException
System.ArrayTypeMismatchException
System.BadImageFormatException
System.CannotUnloadAppDomainException
System.ComponentModel.Design.CheckoutException
System.ComponentModel.Design.Serialization.CodeDomSerializerException
System.ComponentModel.InvalidEnumArgumentException
System.ComponentModel.LicenseException
System.ComponentModel.WarningException
System.ComponentModel.Win32Exception
System.Configuration.ConfigurationException
System.ContextMarshalException
System.Data.ConstraintException
System.Data.DataException
System.Data.DBConcurrencyException
System.Data.DeletedRowInaccessibleException
System.Data.DuplicateNameException
System.Data.EvaluateException
System.Data.ExprException
System.Data.InRowChangingEventException
System.Data.InvalidConstraintException
System.Data.InvalidExpressionException
System.Data.MissingPrimaryKeyException
System.Data.NoNullAllowedException
System.Data.Odbc.OdbcException
System.Data.OleDb.OleDbException
System.Data.ReadOnlyException
System.Data.RowNotInTableException
System.Data.SqlClient._ValueException
System.Data.SqlClient.SqlException
System.Data.SqlTypes.SqlNullValueException
System.Data.SqlTypes.SqlTruncateException
System.Data.SqlTypes.SqlTypeException
System.Data.StrongTypingException
System.Data.SyntaxErrorException
System.Data.TypedDataSetGeneratorException
System.Data.VersionNotFoundException
System.DivideByZeroException
System.DllNotFoundException
System.Drawing.Printing.InvalidPrinterException
System.DuplicateWaitObjectException
System.EntryPointNotFoundException
System.Exception
System.ExecutionEngineException
System.FieldAccessException
System.FormatException
System.IndexOutOfRangeException
System.InvalidCastException
System.InvalidOperationException
System.InvalidProgramException
System.IO.DirectoryNotFoundException
System.IO.EndOfStreamException
System.IO.FileLoadException
System.IO.FileNotFoundException
System.IO.InternalBufferOverflowException
System.IO.IOException
System.IO.IsolatedStorage.IsolatedStorageException
System.IO.PathTooLongException
System.Management.ManagementException
System.MemberAccessException
System.Messaging.MessageQueueException
System.MethodAccessException
System.MissingFieldException
System.MissingMemberException
System.MissingMethodException
System.MulticastNotSupportedException
System.Net.CookieException
System.Net.ProtocolViolationException
System.Net.Sockets.SocketException
System.Net.WebException
System.NotFiniteNumberException
System.NotImplementedException
System.NotSupportedException
System.NullReferenceException
System.ObjectDisposedException
System.OutOfMemoryException
System.OverflowException
System.PlatformNotSupportedException
System.RankException
System.Reflection.AmbiguousMatchException
System.Reflection.CustomAttributeFormatException
System.Reflection.InvalidFilterCriteriaException
System.Reflection.ReflectionTypeLoadException
System.Reflection.TargetException
System.Reflection.TargetInvocationException
System.Reflection.TargetParameterCountException
System.Resources.MissingManifestResourceException
System.Runtime.InteropServices.COMException
System.Runtime.InteropServices.ExternalException
System.Runtime.InteropServices.InvalidComObjectException
System.Runtime.InteropServices.InvalidOleVariantTypeException
System.Runtime.InteropServices.MarshalDirectiveException
System.Runtime.InteropServices.SafeArrayRankMismatchException
System.Runtime.InteropServices.SafeArrayTypeMismatchException
System.Runtime.InteropServices.SEHException
System.Runtime.Remoting.MetadataServices.SUDSGeneratorException
System.Runtime.Remoting.MetadataServices.SUDSParserException
System.Runtime.Remoting.RemotingException
System.Runtime.Remoting.RemotingTimeoutException
System.Runtime.Remoting.ServerException
System.Runtime.Serialization.SerializationException
System.Security.Cryptography.CryptographicException
System.Security.Cryptography.CryptographicUnexpectedOperationException
System.Security.Policy.PolicyException
System.Security.SecurityException
System.Security.VerificationException
System.Security.XmlSyntaxException
System.ServiceProcess.TimeoutException
System.StackOverflowException
System.SystemException
System.Threading.SynchronizationLockException
System.Threading.ThreadAbortException
System.Threading.ThreadInterruptedException
System.Threading.ThreadStateException
System.Threading.ThreadStopException
System.TypeInitializationException
System.TypeLoadException
System.TypeUnloadedException
System.UnauthorizedAccessException
System.UriFormatException
System.Web.HttpApplication+CancelModuleException
System.Web.HttpCompileException
System.Web.HttpException
System.Web.HttpParseException
System.Web.HttpRequestValidationException
System.Web.HttpUnhandledException
System.Web.Services.Discovery.InvalidContentTypeException
System.Web.Services.Discovery.InvalidDocumentContentsException
System.Web.Services.Protocols.SoapException
System.Web.Services.Protocols.SoapHeaderException
System.Windows.Forms.AxHost+InvalidActiveXStateException
System.Xml.Schema.XmlSchemaException
System.Xml.XmlException
System.Xml.XPath.XPathException
System.Xml.Xsl.XsltCompileException
System.Xml.Xsl.XsltException

Posted by Jeff Atwood    View blog reactions

 

« Teaching Users to Read The Antidote to ASP.NET Smart Navigation »

 

Comments

See, I knew you'd write something when the problem bugged you enough! ;)

Great bit of code. All that remains for me to do is look up the exception in the online help if I want more info. When I have a bit of spare time, I could bring the list and the online help together in a web page. Not likely to be soon though, is anyone else able to do this kind of thing?

Thanks very much for the post, Jeff.

Andy on October 27, 2004 08:19 AM

Instead of the regex you could also do:

t.IsSubclassOf(Exception)

Were you so inclined.

sam on October 27, 2004 03:44 PM

There are some undocumented exceptions here as well. I made an ASP.NET application that uses background threading to keep the view (i.e. the browser) alive during some demanding requests on the database (often taking minutes), and would very occasionally catch "Thread_Stop_Exception", without the underscores, which I had to insert because without them this blogging engine judged it to be questionable content, but MSDN has no documentation on this type whatsoever.

Dag Johansen on February 23, 2006 02:04 PM

http://icr.seascape.uk.net/docdump/ExceptionClassList.php
Here is a quick and dirty page which links to the msdn help for each exception. It was very simple, the php code is:
function ExceptionToMSDNUrl($exception)
{
$url = str_replace(".", "", $exception);
$url = strtolower($url);
$url = "http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrf" . $url . "classtopic.asp";
return $url;
}
At the time of writing, it doesn't check to see if MSDN has documentation on the current exception, though that is something I'm thinking of adding. It's just my current methods are far too slow and the page would take a while to load. I may play around with AJAX.

[ICR] on February 24, 2006 04:33 AM

hi jeff, thanks for the idea, i have created based on your code a C# sample.

this is available here: http://netrsc.blogspot.com/2007/02/creating-even-more-exceptional.html

cheers,
roni

roni on February 1, 2007 12:25 PM

nice post. very useful. ...although i haven't used it yet. ;)

angelo on October 4, 2007 07:25 AM

Thank the programming gods for you and Google. You just saved me a lot of work putting together an exception list :)

squidbot on January 25, 2008 06:27 PM

See end for List of exceptions from Framework 3.5)

I modified it so it was
1) In C#
2) Not dependant on the framework version. The drawback is that you need a stack of references added to the solution. (See list below)

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Text.RegularExpressions;
using System.Design;

namespace ExceptionList
{

class Program
{
static void Main(string[] args)
{
ReflectionSearch(".*exception$");
Console.ReadKey();
}
static public void ReflectionSearch(string strPattern)
{
Assembly thisAssembly = Assembly.GetExecutingAssembly();
AssemblyName[] assemblyNames = thisAssembly.GetReferencedAssemblies();
// Force the load of various assemblies
new System.AddIn.Hosting.InvalidPipelineStoreException();
new System.Configuration.Provider.ProviderException();
new System.Configuration.Install.InstallException();
new System.Data.DataException();
new System.Drawing.Color();
new System.Drawing.Design.UITypeEditor();
new System.DirectoryServices.DirectoryEntry();
new System.Management.ConnectionOptions();
new System.Messaging.AccessControlList();
new System.Runtime.Remoting.RemotingException();
new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
new System.Security.HostProtectionException();
new System.ServiceProcess.TimeoutException();
new System.Web.HttpCompileException();
new System.Windows.Forms.Form();
new System.Windows.Forms.Design.AnchorEditor();
new System.Xml.XmlDocument();

Regex regex = new Regex(@"^(?<path>.*)\.(?<exc>.*?)$", RegexOptions.Compiled | RegexOptions.ExplicitCapture);
foreach (var assemblyName in assemblyNames)
{
Assembly assembly = Assembly.Load(assemblyName);
foreach (Module module in assembly.GetModules())
{
SortedList<string, string> moduleList = new SortedList<string, string>();
foreach (Type t in module.GetTypes())
{
if (t.IsSubclassOf(typeof(Exception)))
moduleList.Add(t.FullName, null);
}
if (moduleList.Count > 0)
{
string lastPath = "";
Console.WriteLine(module.Name);
foreach (string excName in moduleList.Keys)
{
Match match = regex.Match(excName);
if (match.Success)
{
string path = match.Groups["path"].Value;
if (path != lastPath)
{
lastPath = path;
Console.WriteLine("\t" + path);
}
Console.WriteLine("\t\t" + match.Groups["exc"].Value);
}
else
Console.WriteLine("Whoops...\t" + excName);
}
}
else
Console.WriteLine(module.Name + " can be taken out of the list");
}
}
}
}
}

References needed (all begin System.xxx)

AddIn
configuration
Configuration.Install
Core
Data
Design
DirectoryService
Drawing
Management
Messaging
RunTimeRemoting
Security
ServiceProcess
Web
Windows.Forms
Xml
Xml.Linq

mscorlib.dll
System
AccessViolationException
AppDomainUnloadedException
ApplicationException
ArgumentException
ArgumentNullException
ArgumentOutOfRangeException
ArithmeticException
ArrayTypeMismatchException
ASSERT
BadImageFormatException
CannotUnloadAppDomainException
System.Collections.Generic
KeyNotFoundException
System
ContextMarshalException
DataMisalignedException
DivideByZeroException
DllNotFoundException
DuplicateWaitObjectException
EntryPointNotFoundException
ExecutionEngineException
FieldAccessException
FormatException
IndexOutOfRangeException
InsufficientMemoryException
InvalidCastException
InvalidOperationException
InvalidProgramException
System.IO
DirectoryNotFoundException
DriveNotFoundException
EndOfStreamException
FileLoadException
FileNotFoundException
IOException
System.IO.IsolatedStorage
IsolatedStorageException
System.IO
PathTooLongException
System
MemberAccessException
MethodAccessException
MissingFieldException
MissingMemberException
MissingMethodException
MulticastNotSupportedException
NotFiniteNumberException
NotImplementedException
NotSupportedException
NullReferenceException
ObjectDisposedException
OperationCanceledException
OutOfMemoryException
OverflowException
PlatformNotSupportedException
RankException
System.Reflection
AmbiguousMatchException
CustomAttributeFormatException
InvalidFilterCriteriaException
MetadataException
ReflectionTypeLoadException
TargetException
TargetInvocationException
TargetParameterCountException
System.Resources
MissingManifestResourceException
MissingSatelliteAssemblyException
System.Runtime.CompilerServices
RuntimeWrappedException
System.Runtime.InteropServices
COMException
ExternalException
InvalidComObjectException
InvalidOleVariantTypeException
MarshalDirectiveException
SafeArrayRankMismatchException
SafeArrayTypeMismatchException
SEHException
System.Runtime.Remoting
RemotingException
RemotingTimeoutException
ServerException
System.Runtime.Serialization
SerializationException
System.Security.AccessControl
PrivilegeNotHeldException
System.Security.Cryptography
CryptographicException
CryptographicUnexpectedOperationException
System.Security
HostProtectionException
System.Security.Policy
PolicyException
System.Security.Principal
IdentityNotMappedException
System.Security
SecurityException
VerificationException
XmlSyntaxException
System
StackOverflowException
SystemException
System.Text
DecoderFallbackException
EncoderFallbackException
System.Threading
AbandonedMutexException
SynchronizationLockException
ThreadAbortException
ThreadInterruptedException
ThreadStartException
ThreadStateException
WaitHandleCannotBeOpenedException
System
TimeoutException
TypeInitializationException
TypeLoadException
TypeUnloadedException
UnauthorizedAccessException
System.AddIn.dll
Microsoft.Contracts
Contract+AssertionException
Contract+AssumptionException
Contract+InvariantException
Contract+PostconditionException
Contract+PreconditionException
System.AddIn.Hosting
AddInBaseInAddInFolderException
AddInSegmentDirectoryNotFoundException
InvalidPipelineStoreException
System.AddIn.MiniReflection
GenericsNotImplementedException
System.Configuration.dll
System.Configuration
ConfigurationErrorsException
System.Configuration.Provider
ProviderException
System.Configuration.Install.dll
System.Configuration.Install
InstallException
System.Data.dll
<CrtImplementationDetails>
ModuleLoadException
ModuleLoadExceptionHandlerException
Microsoft.SqlServer.Server
InvalidUdtException
System.Data.Common
DbException
System.Data
ConstraintException
DataException
DBConcurrencyException
DeletedRowInaccessibleException
DuplicateNameException
EvaluateException
InRowChangingEventException
InvalidConstraintException
InvalidExpressionException
MissingPrimaryKeyException
NoNullAllowedException
System.Data.Odbc
OdbcException
System.Data.OleDb
OleDbException
System.Data
OperationAbortedException
ReadOnlyException
RowNotInTableException
System.Data.SqlClient
SqlException
System.Data.SqlTypes
SqlAlreadyFilledException
SqlNotFilledException
SqlNullValueException
SqlTruncateException
SqlTypeException
System.Data
StrongTypingException
SyntaxErrorException
TypedDataSetGeneratorException
VersionNotFoundException
System.Drawing.dll
System.Drawing.Printing
InvalidPrinterException
System.DirectoryServices.dll
System.DirectoryServices.ActiveDirectory
ActiveDirectoryObjectExistsException
ActiveDirectoryObjectNotFoundException
ActiveDirectoryOperationException
ActiveDirectoryServerDownException
ForestTrustCollisionException
SyncFromAllServersOperationException
System.DirectoryServices
DirectoryServicesCOMException
System.Management.dll
System.Management
ManagementException
System.Messaging.dll
System.Messaging
MessageQueueException
System.Runtime.Serialization.Formatters.Soap.dll can be taken out of the list
System.ServiceProcess.dll
System.ServiceProcess
TimeoutException
System.Web.dll
System.Web.Caching
DatabaseNotEnabledForNotificationException
TableNotEnabledForNotificationException
System.Web.Hosting
HostingEnvironmentException
System.Web
HttpCompileException
HttpException
HttpParseException
HttpRequestValidationException
HttpUnhandledException
System.Web.Management
SqlExecutionException
System.Web.Security
MembershipCreateUserException
MembershipPasswordException
System.Web.UI
ViewStateException
System.Windows.Forms.dll
System.Windows.Forms
AxHost+InvalidActiveXStateException
System.Design.dll
System.ComponentModel.Design
ExceptionCollection
System.ComponentModel.Design.Serialization
CodeDomSerializerException
System.Data.Design
DataSourceGeneratorException
DataSourceSerializationException
InternalException
NameValidationException
TypedDataSetGeneratorException
System.Xml.dll
System.Xml.Schema
UpaException
XmlSchemaException
XmlSchemaInferenceException
XmlSchemaValidationException
System.Xml
XmlException
System.Xml.XPath
XPathException
System.Xml.Xsl
XsltCompileException
XsltException
System.dll
System.ComponentModel.Design
CheckoutException
System.ComponentModel
InvalidAsynchronousStateException
InvalidEnumArgumentException
LicenseException
WarningException
Win32Exception
System.Configuration
ConfigurationException
SettingsPropertyIsReadOnlyException
SettingsPropertyNotFoundException
SettingsPropertyWrongTypeException
System.IO
InternalBufferOverflowException
InvalidDataException
System.Net
CookieException
HttpListenerException
InternalException
System.Net.Mail
SmtpException
SmtpFailedRecipientException
SmtpFailedRecipientsException
System.Net.NetworkInformation
NetworkInformationException
PingException
System.Net
ProtocolViolationException
System.Net.Sockets
SocketException
System.Net
WebException
System.Security.Authentication
AuthenticationException
InvalidCredentialException
System.Threading
SemaphoreFullException
System
UriFormatException

Paul Cotter on February 1, 2008 08:12 AM

Bugger it. The formatting is screwed. Oh well, cut and paste the code and go Ctrl-K Ctrl-D

Paul Cotter on February 1, 2008 08:15 AM

Thanks Jeff. This was useful for me today.

Terrapin on July 16, 2008 09:01 AM







(hear it spoken)


(no HTML)




Content (c) 2008 Jeff Atwood. Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved.