System.Exception Class

Represents errors that occur during application execution.

See Also: Exception Members

Syntax

[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComDefaultInterface(typeof(System.Runtime.InteropServices._Exception))]
[System.Runtime.InteropServices.ComVisible(true)]
public class Exception : System.Runtime.InteropServices._Exception, System.Runtime.Serialization.ISerializable

Remarks

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 that contains information about the error. After an exception is thrown, it is handled by the application or by the default exception handler.

In this section:

Errors and exceptions Try/catch blocks Exception type features Exception class properties Performance considerations Choosing standard exceptions Implementing custom exceptions

Errors and exceptions

Run-time errors can occur for a variety of reasons. However, not all errors should be handled as exceptions in your code. Here are some categories of errors that can occur at run time and the appropriate ways to respond to them.

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. 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 and is called 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:

Exception class properties

The Exception class includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: Exception.StackTrace, Exception.InnerException, Exception.Message, Exception.HelpLink, Exception.HResult, Exception.Source, Exception.TargetSite, and Exception.Data.

When a causal relationship exists between two or more exceptions, the Exception.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 Exception.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 System.Resources.ResourceManager class. For more information about localized resources, see the Creating Satellite Assemblies for Desktop Apps and Packaging and Deploying Resources topics.

To provide the user with extensive information about why the exception occurred, the Exception.HelpLink property can hold a URL (or URN) to a help file.

The Exception class uses the HRESULT COR_E_EXCEPTION, which has the value 0x80131500.

For a list of initial property values for an instance of the Exception class, see the Exception.#ctor constructors.

Performance considerations

Throwing or handling an exception consumes a significant amount of system resources and execution time. Throw exceptions only to handle truly extraordinary conditions, not to handle predictable events or flow control. For example, it's reasonable to throw an exception if a method argument is invalid, because you expect to call your method with valid parameters. An invalid method argument means that 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. Instead, 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, and then continue processing.

Choosing standard exceptions

When you have to throw an exception, you can often use an existing exception type in the .NET Framework instead of implementing a custom exception. You should use a standard exception type under these two conditions:

Implementing custom exceptions

In the following cases, using an existing .NET Framework exception to handle an error condition is not adequate:

The Exception class is the base class of all exceptions in the .NET Framework. Many derived classes rely on the inherited behavior of the members of the Exception class; they do not override the members of Exception, nor do they define any unique members.

To define your own exception class:

[The 'ordered' type of list has not been implemented in the ECMA stylesheet.]

The following example illustrates the use of a custom exception class. It defines a NotPrimeException exception that is thrown when a client tries 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 System.Runtime.Serialization.SerializationInfo and System.Runtime.Serialization.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.

code reference: System.Exception.Class#1

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.

code reference: System.Exception.Class#2

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.

code reference: System.Exception.Class#3

Windows Runtime and net_v451

In net_win8_profile for win8, some exception information is typically lost when an exception is propagated through non-.NET Framework stack frames. Starting with the net_v451 and win81, the common language runtime continues to use the original Exception object that was thrown unless that exception was modified in a non-.NET Framework stack frame.

Thread Safety

All public static members of this type are safe for multithreaded operations. No instance members are guaranteed to be thread safe.

Example

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.

C# Example

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());
 }
 } 
}
   

The output is

Example

ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero.
   at ExceptionTestClass.Main()
 

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0