Exception Class
Represents errors that occur during application execution.
Assembly: mscorlib (in mscorlib.dll)
The Exception type exposes the following members.
| Name | Description | |
|---|---|---|
![]() ![]() ![]() ![]() | Exception() | Initializes a new instance of the Exception class. |
![]() ![]() ![]() ![]() | Exception(String) | Initializes a new instance of the Exception class with a specified error message. |
![]() | Exception(SerializationInfo, StreamingContext) | Initializes a new instance of the Exception class with serialized data. |
![]() ![]() ![]() ![]() | Exception(String, Exception) | Initializes a new instance of the Exception class with a specified error message and a reference to the inner exception that is the cause of this exception. |
| Name | Description | |
|---|---|---|
![]() ![]() ![]() | Data | Gets a collection of key/value pairs that provide additional user-defined information about the exception. |
![]() ![]() ![]() | HelpLink | Gets or sets a link to the help file associated with this exception. |
![]() ![]() ![]() ![]() | HResult | Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. |
![]() ![]() ![]() ![]() | InnerException | Gets the Exception instance that caused the current exception. |
![]() ![]() ![]() ![]() | Message | Gets a message that describes the current exception. |
![]() ![]() ![]() | Source | Gets or sets the name of the application or the object that causes the error. |
![]() ![]() ![]() ![]() | StackTrace | Gets a string representation of the immediate frames on the call stack. |
![]() | TargetSite | Gets the method that throws the current exception. |
| Name | Description | |
|---|---|---|
![]() ![]() ![]() ![]() | Equals(Object) | Determines whether the specified object is equal to the current object. (Inherited from Object.) |
![]() ![]() ![]() ![]() | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) |
![]() ![]() ![]() ![]() | GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. |
![]() ![]() ![]() ![]() | GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) |
![]() | GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. |
![]() ![]() ![]() ![]() | GetType | Gets the runtime type of the current instance. In XNA Framework 3.0, this member is inherited from Object.GetType(). In Portable Class Library Portable Class Library, this member is inherited from Object.GetType(). In .NET for Windows Store apps Windows 8, this member is inherited from Object.GetType(). |
![]() ![]() ![]() ![]() | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) |
![]() ![]() ![]() ![]() | ToString | Creates and returns a string representation of the current exception. (Overrides Object.ToString().) |
| Name | Description | |
|---|---|---|
![]() | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. |
This class is the base class for all exceptions. When an error occurs, either the system or the currently executing application reports it by throwing an exception containing information about the error. Once thrown, an exception is handled by the application or by the default exception handler.
Try/Catch Blocks
The common language runtime provides an exception handling model that is based on the representation of exceptions as objects, and the separation of program code and exception handling code into try blocks and catch blocks, respectively. There can be one or more catch blocks, each designed to handle a particular type of exception, or one block designed to catch a more specific exception than another block.
If an application handles exceptions that occur during the execution of a block of application code, the code must be placed within a try statement. Application code within a try statement is a try block. Application code that handles exceptions thrown by a try block is placed within a catch statement, and is called a catch block. Zero or more catch blocks are associated with a try block, and each catch block includes a type filter that determines the types of exceptions it handles.
When an exception occurs in a try block, the system searches the associated catch blocks in the order they appear in application code, until it locates a catch block that handles the exception. A catch block handles an exception of type T if the type filter of the catch block specifies T or any type that T derives from. The system stops searching after it finds the first catch block that handles the exception. For this reason, in application code, a catch block that handles a type must be specified before a catch block that handles its base types, as demonstrated in the example that follows this section. A catch block that handles System.Exception is specified last.
If none of the catch blocks associated with the current try block handle the exception, and the current try block is nested within other try blocks in the current call, the catch blocks associated with the next enclosing try block are searched. If no catch block for the exception is found, the system searches previous nesting levels in the current call. If no catch block for the exception is found in the current call, the exception is passed up the call stack, and the previous stack frame is searched for a catch block that handles the exception. The search of the call stack continues until the exception is handled or until no more frames exist on the call stack. If the top of the call stack is reached without finding a catch block that handles the exception, the default exception handler handles it and the application terminates.
Exception Type Features
Exception types support the following features:
Human-readable text that describes the error. When an exception occurs, the runtime makes available a text message to inform the user of the nature of the error and to suggest action to resolve the problem. This text message is held in the Message property of the exception object. During the creation of the exception object, you can pass a text string to the constructor to describe the details of that particular exception. If no error message argument is supplied to the constructor, the default error message is used.
The state of the call stack when the exception was thrown. The StackTrace property carries a stack trace that can be used to determine where in the code the error occurs. The stack trace lists all the called methods, and the line numbers in the source file where the calls are made.
Exception Class Properties
Exception includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: StackTrace, InnerException, Message, HelpLink, HResult, Source, TargetSite, and Data.
When a causal relationship exists between two or more exceptions, the InnerException property maintains this information. The outer exception is thrown in response to this inner exception. The code that handles the outer exception can use the information from the earlier inner exception to handle the error more appropriately. Supplementary information about the exception can be stored as a collection of key/value pairs in the Data property.
The error message string that is passed to the constructor during the creation of the exception object should be localized and can be supplied from a resource file by using the ResourceManager class. For more information about localized resources, see the Creating Satellite Assemblies for Desktop Apps and Packaging and Deploying Resources in Desktop Apps topics.
To provide the user with extensive information concerning why the exception occurred, the HelpLink property can hold a URL (or URN) to a help file.
Exception uses the HRESULT COR_E_EXCEPTION, which has the value 0x80131500.
For a list of initial property values for an instance of Exception, see the Exception constructors.
Performance Considerations
A significant amount of system resources and execution time are used when you throw or handle an exception. Throw exceptions only to handle truly extraordinary conditions, not to handle predictable events or flow control. For example, your application can reasonably throw an exception if a method argument is invalid because you expect to call your method with valid parameters. An invalid method argument means something extraordinary has occurred. Conversely, do not throw an exception if user input is invalid because you can expect users to occasionally enter invalid data. In such a case, provide a retry mechanism so users can enter valid input.
In addition, do not throw an exception when a return code is sufficient; do not convert a return code to an exception; and do not routinely catch an exception, ignore it, then continue processing.
Implementing Custom Exceptions
The Exception class is the base class of all exceptions in the .NET Framework. Many of these derived classes do not override the members of Exception, nor do they define any unique members; they rely on the inherited behavior of the members of the Exception class.
To define your own exception class, do the following:
Define a class that inherits from Exception. Define any unique members needed by your class to provide additional information about the exception. For example, the ArgumentException class includes a ParamName property that specifies the name of the parameter whose argument caused the exception, and the RegexMatchTimeoutException property includes a MatchTimeout property that indicates the time-out interval.
Override any inherited members whose functionality you want to change or modify.
Determine whether your custom exception object is serializable. Serialization enables you to save information about the exception, and permits exception information to be shared by a server and a client proxy in a remoting context. To make the exception object serializable, mark it with the SerializableAttribute attribute.
Define the constructors of your exception class. Typically, exception classes have one or more of the following constructors:
Exception(), which uses default values to initialize the properties of a new exception object.
Exception(String), which initializes a new exception object with a specified error message.
Exception(String, Exception), which initializes a new exception object with a specified error message and inner exception.
Exception(SerializationInfo, StreamingContext), a protected constructor that initializes a new exception object from serialized data. You should implement this constructor if you've chosen to make your exception object serializable.
The following example illustrates the use of a custom exception class. It defines a NotPrimeException exception that is thrown when a client attempts to retrieve a sequence of prime numbers by specifying a starting number that is not prime. The exception defines a new property, NonPrime, that returns the non-prime number that caused the exception. Besides implementing a protected parameterless constructor and a constructor with SerializationInfo and StreamingContext parameters for serialization, the NotPrimeException class defines three additional constructors to support the NonPrime property. Each constructor calls a base class constructor in addition to preserving the value of the non-prime number. The NotPrimeException class is also marked with the SerializableAttribute attribute.
using System; using System.Runtime.Serialization; [Serializable()] public class NotPrimeException : Exception { private int notAPrime; protected NotPrimeException() : base() { } public NotPrimeException(int value) : base(String.Format("{0} is not a prime number.", value)) { notAPrime = value; } public NotPrimeException(int value, string message) : base(message) { notAPrime = value; } public NotPrimeException(int value, string message, Exception innerException) : base(message, innerException) { notAPrime = value; } protected NotPrimeException(SerializationInfo info, StreamingContext context) : base(info, context) { } public int NonPrime { get { return notAPrime; } } }
The PrimeNumberGenerator class shown in the following example uses the Sieve of Eratosthenes to calculate the sequence of prime numbers from 2 to a limit specified by the client in the call to its class constructor. The GetPrimesFrom method returns all prime numbers that are greater than or equal to a specified lower limit, but throws a NotPrimeException if that lower limit is not a prime number.
using System; using System.Collections.Generic; [Serializable] public class PrimeNumberGenerator { private const int START = 2; private int maxUpperBound = 10000000; private int upperBound; private bool[] primeTable; private List<int> primes = new List<int>(); public PrimeNumberGenerator(int upperBound) { if (upperBound > maxUpperBound) { string message = String.Format( "{0} exceeds the maximum upper bound of {1}.", upperBound, maxUpperBound); throw new ArgumentOutOfRangeException(message); } this.upperBound = upperBound; // Create array and mark 0, 1 as not prime (True). primeTable = new bool[upperBound + 1]; primeTable[0] = true; primeTable[1] = true; // Use Sieve of Eratosthenes to determine prime numbers. for (int ctr = START; ctr <= (int)Math.Ceiling(Math.Sqrt(upperBound)); ctr++) { if (primeTable[ctr]) continue; for (int multiplier = ctr; multiplier <= upperBound / ctr; multiplier++) if (ctr * multiplier <= upperBound) primeTable[ctr * multiplier] = true; } // Populate array with prime number information. int index = START; while (index != -1) { index = Array.FindIndex(primeTable, index, (flag) => !flag); if (index >= 1) { primes.Add(index); index++; } } } public int[] GetAllPrimes() { return primes.ToArray(); } public int[] GetPrimesFrom(int prime) { int start = primes.FindIndex((value) => value == prime); if (start < 0) throw new NotPrimeException(prime, String.Format("{0} is not a prime number.", prime)); else return primes.FindAll((value) => value >= prime).ToArray(); } }
The following example makes two calls to the GetPrimesFrom method with non-prime numbers, one of which crosses application domain boundaries. In both cases, the exception is thrown and successfully handled in client code.
using System; using System.Reflection; class Example { public static void Main() { int limit = 10000000; PrimeNumberGenerator primes = new PrimeNumberGenerator(limit); int start = 1000001; try { int[] values = primes.GetPrimesFrom(start); Console.WriteLine("There are {0} prime numbers from {1} to {2}", start, limit); } catch (NotPrimeException e) { Console.WriteLine("{0} is not prime", e.NonPrime); Console.WriteLine(e); Console.WriteLine("--------"); } AppDomain domain = AppDomain.CreateDomain("Domain2"); PrimeNumberGenerator gen = (PrimeNumberGenerator)domain.CreateInstanceAndUnwrap( typeof(Example).Assembly.FullName, "PrimeNumberGenerator", true, BindingFlags.Default, null, new object[] { 1000000 }, null, null); try { start = 100; Console.WriteLine(gen.GetPrimesFrom(start)); } catch (NotPrimeException e) { Console.WriteLine("{0} is not prime", e.NonPrime); Console.WriteLine(e); Console.WriteLine("--------"); } } }
The following example demonstrates a catch block that is defined to handle ArithmeticException errors. This catch block also catches DivideByZeroException errors because DivideByZeroException derives from ArithmeticException, and there is no catch block explicitly defined for DivideByZeroException errors.
using System; class ExceptionTestClass { public static void Main() { int x = 0; try { int y = 100/x; } catch (ArithmeticException e) { Console.WriteLine("ArithmeticException Handler: {0}", e.ToString()); } catch (Exception e) { Console.WriteLine("Generic Exception Handler: {0}", e.ToString()); } } } /* This code example produces the following results: ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero. at ExceptionTestClass.Main() */
Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
System.Exception
Microsoft.Build.BuildEngine.InternalLoggerException
Microsoft.Build.BuildEngine.InvalidProjectFileException
Microsoft.Build.BuildEngine.InvalidToolsetDefinitionException
Microsoft.Build.BuildEngine.RemoteErrorException
Microsoft.Build.Exceptions.BuildAbortedException
Microsoft.Build.Exceptions.InternalLoggerException
Microsoft.Build.Exceptions.InvalidProjectFileException
Microsoft.Build.Exceptions.InvalidToolsetDefinitionException
Microsoft.Build.Framework.LoggerException
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
Microsoft.CSharp.RuntimeBinder.RuntimeBinderInternalCompilerException
Microsoft.JScript.CmdLineException
Microsoft.JScript.ParserException
Microsoft.VisualBasic.ApplicationServices.CantStartSingleInstanceException
Microsoft.VisualBasic.ApplicationServices.NoStartupFormException
Microsoft.VisualBasic.Compatibility.VB6.WebClassContainingClassNotOptional
Microsoft.VisualBasic.Compatibility.VB6.WebClassCouldNotFindEvent
Microsoft.VisualBasic.Compatibility.VB6.WebClassNextItemCannotBeCurrentWebItem
Microsoft.VisualBasic.Compatibility.VB6.WebClassNextItemRespondNotFound
Microsoft.VisualBasic.Compatibility.VB6.WebClassUserWebClassNameNotOptional
Microsoft.VisualBasic.Compatibility.VB6.WebClassWebClassFileNameNotOptional
Microsoft.VisualBasic.Compatibility.VB6.WebClassWebItemNotValid
Microsoft.VisualBasic.Compatibility.VB6.WebItemAssociatedWebClassNotOptional
Microsoft.VisualBasic.Compatibility.VB6.WebItemClosingTagNotFound
Microsoft.VisualBasic.Compatibility.VB6.WebItemCouldNotLoadEmbeddedResource
Microsoft.VisualBasic.Compatibility.VB6.WebItemCouldNotLoadTemplateFile
Microsoft.VisualBasic.Compatibility.VB6.WebItemNameNotOptional
Microsoft.VisualBasic.Compatibility.VB6.WebItemNoTemplateSpecified
Microsoft.VisualBasic.Compatibility.VB6.WebItemTooManyNestedTags
Microsoft.VisualBasic.Compatibility.VB6.WebItemUnexpectedErrorReadingTemplateFile
Microsoft.VisualBasic.CompilerServices.IncompleteInitialization
Microsoft.VisualBasic.CompilerServices.InternalErrorException
Microsoft.VisualBasic.FileIO.MalformedLineException
System.Activities.DynamicUpdate.InstanceUpdateException
System.Activities.ExpressionParser.SourceExpressionException
System.Activities.Expressions.LambdaSerializationException
System.Activities.InvalidWorkflowException
System.Activities.Presentation.Metadata.AttributeTableValidationException
System.Activities.Statements.WorkflowTerminatedException
System.Activities.VersionMismatchException
System.Activities.WorkflowApplicationException
System.AddIn.Hosting.AddInSegmentDirectoryNotFoundException
System.AddIn.Hosting.InvalidPipelineStoreException
System.AggregateException
System.ApplicationException
System.ComponentModel.Composition.CompositionContractMismatchException
System.ComponentModel.Composition.CompositionException
System.ComponentModel.Composition.ImportCardinalityMismatchException
System.ComponentModel.Composition.Primitives.ComposablePartException
System.ComponentModel.DataAnnotations.ValidationException
System.ComponentModel.Design.ExceptionCollection
System.Configuration.Provider.ProviderException
System.Configuration.SettingsPropertyIsReadOnlyException
System.Configuration.SettingsPropertyNotFoundException
System.Configuration.SettingsPropertyWrongTypeException
System.Data.Linq.ChangeConflictException
System.Diagnostics.Eventing.Reader.EventLogException
System.Diagnostics.Tracing.EventSourceException
System.DirectoryServices.ActiveDirectory.ActiveDirectoryObjectExistsException
System.DirectoryServices.ActiveDirectory.ActiveDirectoryObjectNotFoundException
System.DirectoryServices.ActiveDirectory.ActiveDirectoryOperationException
System.DirectoryServices.ActiveDirectory.ActiveDirectoryServerDownException
System.DirectoryServices.Protocols.DirectoryException
System.IdentityModel.AsynchronousOperationException
System.IdentityModel.Metadata.MetadataSerializationException
System.IdentityModel.Protocols.WSTrust.WSTrustSerializationException
System.IdentityModel.RequestException
System.IdentityModel.Selectors.CardSpaceException
System.IdentityModel.Selectors.IdentityValidationException
System.IdentityModel.Selectors.PolicyValidationException
System.IdentityModel.Selectors.ServiceBusyException
System.IdentityModel.Selectors.ServiceNotStartedException
System.IdentityModel.Selectors.StsCommunicationException
System.IdentityModel.Selectors.UnsupportedPolicyOptionsException
System.IdentityModel.Selectors.UntrustedRecipientException
System.IdentityModel.Selectors.UserCancellationException
System.IdentityModel.Services.AsynchronousOperationException
System.IdentityModel.Services.FederatedAuthenticationSessionEndingException
System.IdentityModel.Services.FederationException
System.IdentityModel.Services.WSFederationMessageException
System.InvalidTimeZoneException
System.IO.IsolatedStorage.IsolatedStorageException
System.IO.Log.SequenceFullException
System.Management.Instrumentation.InstrumentationBaseException
System.Management.Instrumentation.WmiProviderInstallationException
System.Net.Http.HttpRequestException
System.Net.Mail.SmtpException
System.Net.PeerToPeer.PeerToPeerException
System.Runtime.CompilerServices.RuntimeWrappedException
System.Runtime.DurableInstancing.InstancePersistenceException
System.Runtime.Remoting.MetadataServices.SUDSGeneratorException
System.Runtime.Remoting.MetadataServices.SUDSParserException
System.Runtime.Serialization.InvalidDataContractException
System.Security.RightsManagement.RightsManagementException
System.ServiceModel.Channels.InvalidChannelBindingException
System.SystemException
System.Threading.BarrierPostPhaseException
System.Threading.LockRecursionException
System.Threading.Tasks.TaskSchedulerException
System.TimeZoneNotFoundException
System.Web.Query.Dynamic.ParseException
System.Web.Security.MembershipCreateUserException
System.Web.Security.MembershipPasswordException
System.Web.UI.ViewStateException
System.Web.UI.WebControls.EntityDataSourceValidationException
System.Web.UI.WebControls.LinqDataSourceValidationException
System.Windows.Automation.NoClickablePointException
System.Windows.Automation.ProxyAssemblyNotLoadedException
System.Windows.Controls.PrintDialogException
System.Windows.Forms.AxHost.InvalidActiveXStateException
System.Windows.Xps.XpsException
System.Windows.Xps.XpsWriterException
System.Workflow.Activities.Rules.RuleException
System.Workflow.ComponentModel.Compiler.WorkflowValidationFailedException
System.Workflow.ComponentModel.Serialization.WorkflowMarkupSerializationException
System.Workflow.ComponentModel.WorkflowTerminatedException
System.Workflow.Runtime.WorkflowOwnershipException
System.Xaml.XamlException



