HOWTO · Csharp

List of Exceptions in C#

We'll look at the C# exceptions that may be thrown in this article.

On this page

C# uses exceptions to report failures during program execution. Specific exception types describe what went wrong, while System.Exception is the common base type for the .NET exception hierarchy. This catalog highlights useful types from several namespaces; it is not a complete inventory, and available types can vary by .NET implementation and version.

Choosing and handling C# exceptions

Choose a type that describes the failure your code can actually encounter. For caller-supplied values, validate inputs and report argument problems with ArgumentNullException, ArgumentOutOfRangeException, or ArgumentException. For an operation that cannot proceed in the object’s current state, InvalidOperationException is often appropriate. Use NotSupportedException when an operation is not supported by that implementation, rather than merely unavailable in the current state.

Catch an exception where the program can recover, add useful context, or translate it at a layer boundary. Catch the most specific type first. Avoid catching System.Exception just to continue as though an operation succeeded; log or propagate failures that the current layer cannot handle. When rethrowing the same failure, use throw; to preserve its original stack trace. Use throw new ... only when translating the failure, and retain the original as the inner exception when it helps diagnosis.

A parse operation can report whether user input is usable without relying on control flow through a thrown exception. The following source is self-contained; it has not been executed in this article-writing step. For the supplied input, its defined output is Accepted: 42.

The sample uses a fixed string so you can focus on the control flow. In an application, replace it with a value received from a form, command line, or file. The TryParse call assigns value on both outcomes. Its parsed value is meaningful only when the method returns true; when it returns false, value is the default int value and the failure branch handles the input. This keeps routine input checking explicit and lets the program continue along its normal path. You can change the string to another whole number and adapt the displayed message to the needs of your application.

Run this example:

using System;

class Program
{
    static void Main()
    {
        string input = "42";
        if (int.TryParse(input, out int value))
        {
            Console.WriteLine($"Accepted: {value}");
        }
        else
        {
            Console.WriteLine("Enter a whole number.");
        }
    }
}

TryParse is useful when a failed conversion is an expected result that the caller can handle directly. When an API instead signals failure by throwing, catch its documented, expected types and leave unrelated failures visible.

System exceptions in C#

These types are found across the .NET base libraries. The list is selective: several are uncommon or tied to specialized runtime behavior, so most application code should prefer the more specific types documented by the API it calls.

  1. AccessViolationException - An attempt to access protected memory was detected; this is generally associated with unsafe or unmanaged code.
  2. AppDomainUnloadedException - Code attempted to use an application domain that has been unloaded.
  3. ApplicationException - A legacy base type for application-defined failures; custom types generally derive from System.Exception instead.
  4. ArgumentException - A method received an argument that does not meet its requirements.
  5. ArgumentNullException - A method received null where it does not allow it.
  6. ArgumentOutOfRangeException - An argument value falls outside the range accepted by the method.
  7. ArithmeticException - A base type for arithmetic-related failures, including DivideByZeroException and OverflowException.
  8. ArrayTypeMismatchException - An attempt to store an incompatible value in an array failed, usually in a covariant array scenario.
  9. BadImageFormatException - A file could not be loaded as a valid assembly or module, often because its format or architecture is incompatible.
  10. CannotUnloadAppDomainException - An attempt to unload an application domain failed; this is mainly relevant to .NET Framework scenarios.
  11. ContextMarshalException - An object could not be marshaled across a remoting context boundary; this is specialized runtime behavior.
  12. DataMisalignedException - Data access required alignment that the platform or operation could not satisfy.
  13. DivideByZeroException - An integral or decimal division operation used a divisor of zero.
  14. DllNotFoundException - A native library named by an import could not be found.
  15. DuplicateWaitObjectException - A wait operation received the same wait handle more than once.
  16. EntryPointNotFoundException - A requested entry point could not be found in a native library or target module.
  17. ExecutionEngineException - A legacy runtime failure type; it is obsolete and should not be used for ordinary application errors.
  18. FieldAccessException - Code could not access a field, commonly because of visibility or access restrictions.
  19. FormatException - A value’s format is unsuitable for the operation, such as parsing text that does not match the expected format.
  20. IndexOutOfRangeException - An array index is outside the array’s valid range. The type is sealed.
  21. InsufficientMemoryException - A memory availability check or allocation-related operation could not provide the requested memory; this type is sealed.
  22. InvalidCastException - An explicit conversion between incompatible types failed.
  23. InvalidOperationException - A method call is not valid for the object’s current state.
  24. InvalidProgramException - The runtime could not execute a program because its intermediate language or metadata is invalid; this often points to a build or toolchain problem.
  25. MemberAccessException - A base type for failures to access a member.
  26. MethodAccessException - Code could not access a method, commonly because of visibility or access restrictions.
  27. MissingFieldException - A requested field could not be found when loading or accessing a type.
  28. MissingMemberException - A requested member could not be found.
  29. MissingMethodException - A requested method could not be found when loading or accessing a type.
  30. MulticastNotSupportedException - An operation attempted to combine delegates in a way that the delegate type does not support.
  31. NotFiniteNumberException - A legacy arithmetic type for a value that is not finite, such as NaN or infinity; modern code commonly checks numeric values directly.
  32. NotImplementedException - A member is declared but its implementation is not yet available. Do not use it to signal an operation that is intentionally unsupported.
  33. NotSupportedException - The requested operation is not supported by the object or implementation.
  34. NullReferenceException - Code attempted to use a member on a null reference. Find and correct the unexpected null rather than using this type for input validation.
  35. ObjectDisposedException - Code attempted to use an object after it was disposed.
  36. OperationCanceledException - An operation was canceled; TaskCanceledException is a derived type often seen with tasks.
  37. OutOfMemoryException - The runtime could not allocate required memory. Applications generally cannot recover reliably from this condition.
  38. OverflowException - A checked arithmetic operation or conversion produced a value outside the target type’s range.
  39. PlatformNotSupportedException - A feature is unavailable on the current platform.
  40. RankException - An array operation received an array with an unsupported number of dimensions.
  41. StackOverflowException - The execution stack was exhausted, commonly by unbounded recursion. Recovery is generally not practical.
  42. SystemException - A base type used by many system-defined exceptions; application code should usually catch a more specific derived type.
  43. TimeoutException - An operation did not complete within its allotted time. Whether it can be retried depends on the operation.
  44. TypeInitializationException - A type initializer failed; inspect its InnerException for the underlying cause.
  45. TypeLoadException - The runtime could not load a type, for example because it could not resolve the type definition.
  46. TypeUnloadedException - Code attempted to use a type associated with an unloaded application domain; this is relevant to runtimes that support application domains.
  47. UnauthorizedAccessException - The operating system or resource denied the requested access.

System.Data exceptions in C#

These types are associated with data tables, constraints, and related ADO.NET operations. Database providers can also expose their own exception types, so inspect provider-specific details when diagnosing a database failure.

  1. ConstraintException - A data operation violated a constraint in a DataSet or related in-memory data structure.
  2. DataException - A base type for errors raised by data-related components.
  3. DBConcurrencyException - An update, insert, or delete operation did not affect the expected row, often because the data changed after it was read.
  4. DeletedRowInaccessibleException - Code attempted to access a row after it was deleted.
  5. DuplicateNameException - An operation attempted to add a table or column with a name already in use.
  6. EvaluateException - An expression could not be evaluated.
  7. InRowChangingEventException - An operation was attempted during a row-changing event when that operation is not allowed.
  8. InvalidConstraintException - A constraint could not be created or used as requested.
  9. InvalidExpressionException - A data expression has invalid syntax or cannot be evaluated as specified.
  10. MissingPrimaryKeyException - An operation required a table’s primary key, but none was defined.
  11. NoNullAllowedException - A null value was assigned to a column that disallows nulls.
  12. OperationAbortedException - A data operation was canceled or aborted.
  13. ReadOnlyException - Code attempted to change a read-only column or value.
  14. RowNotInTableException - Code attempted an operation on a row that does not belong to the table.
  15. StrongTypingException - A strongly typed DataSet property could not convert its underlying value to the requested type.
  16. SyntaxErrorException - A data expression contains a syntax error.
  17. TypedDataSetGeneratorException - The typed DataSet generator encountered an error.
  18. VersionNotFoundException - The requested row version is unavailable.

System.IO exceptions in C#

File and stream APIs commonly report these types. Handle only failures for which the application has a recovery path, such as asking for a different path or retrying a transient read.

  1. DirectoryNotFoundException - A required directory could not be found.
  2. DriveNotFoundException - A required drive or mapped location is unavailable.
  3. EndOfStreamException - A read operation went beyond the end of a stream that has a defined end.
  4. FileLoadException - An assembly was found but could not be loaded.
  5. FileNotFoundException - A required file could not be found.
  6. IOException - A base type for input/output failures, including many file and stream errors.
  7. PathTooLongException - A path exceeded a limit imposed by the operating system or API in use; path limits depend on platform and configuration.

System.Net exceptions in C#

Network failures can arise from DNS, connection, protocol, and remote-service conditions. The exact exception depends on the API and .NET version; inspect inner exceptions and response details when available.

  1. HttpListenerException - An HttpListener operation failed, with an associated native error code.
  2. ProtocolViolationException - A network operation violated the protocol expected by the API.
  3. WebException - A request using a web protocol failed, timed out, or received an unsuccessful response. Newer HTTP APIs may use different exception types.

System.Net.Mail exceptions in C#

SMTP operations can fail at the transport level or for particular recipients. The API’s exception data can include server status information; avoid logging message contents or credentials.

  1. SmtpException - An SMTP operation failed for a general transport or server-related reason.
  2. SmtpFailedRecipientException - Sending failed for one recipient; this derives from SmtpException.
  3. SmtpFailedRecipientsException - Sending failed for multiple recipients; inspect its recipient-specific details.

System.Net.NetworkInformation exceptions in C#

These types can be returned by network information APIs. A failure to obtain local network details does not necessarily mean that a remote service is unavailable.

  1. NetworkInformationException - A network information operation failed, often with an underlying system error code.
  2. PingException - A ping operation failed because its underlying operation raised an error; inspect the inner exception for details.

System.Resources exceptions in C#

Resource failures often indicate a deployment or localization configuration issue. Check resource names, build actions, and satellite assembly packaging before treating them as transient.

  1. MissingManifestResourceException - The main resource manifest required by the application could not be found.
  2. MissingSatelliteAssemblyException - A required satellite assembly for a localized resource set could not be found.