.NET Framework Class Library
Exception Class

Represents errors that occur during application execution.

To browse the .NET Framework source code for this type, see the Reference Source.

Inheritance Hierarchy
SystemObject
  SystemException
    More...

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)
Syntax
<[%$TOPIC/c18k6c59_en-us_VS_110_3_0_0_0_0%]> _
<[%$TOPIC/c18k6c59_en-us_VS_110_3_0_0_0_1%](True)> _
<[%$TOPIC/c18k6c59_en-us_VS_110_3_0_0_0_2%]([%$TOPIC/c18k6c59_en-us_VS_110_3_0_0_0_3%].None)> _
Public Class Exception _
	Implements [%$TOPIC/c18k6c59_en-us_VS_110_3_0_0_0_4%], [%$TOPIC/c18k6c59_en-us_VS_110_3_0_0_0_5%]
[[%$TOPIC/c18k6c59_en-us_VS_110_3_0_1_0_0%]]
[[%$TOPIC/c18k6c59_en-us_VS_110_3_0_1_0_1%](true)]
[[%$TOPIC/c18k6c59_en-us_VS_110_3_0_1_0_2%]([%$TOPIC/c18k6c59_en-us_VS_110_3_0_1_0_3%].None)]
public class Exception : [%$TOPIC/c18k6c59_en-us_VS_110_3_0_1_0_4%], [%$TOPIC/c18k6c59_en-us_VS_110_3_0_1_0_5%]
[[%$TOPIC/c18k6c59_en-us_VS_110_3_0_2_0_0%]]
[[%$TOPIC/c18k6c59_en-us_VS_110_3_0_2_0_1%](true)]
[[%$TOPIC/c18k6c59_en-us_VS_110_3_0_2_0_2%]([%$TOPIC/c18k6c59_en-us_VS_110_3_0_2_0_3%]::None)]
public ref class Exception : [%$TOPIC/c18k6c59_en-us_VS_110_3_0_2_0_4%], 
	[%$TOPIC/c18k6c59_en-us_VS_110_3_0_2_0_5%]
[<[%$TOPIC/c18k6c59_en-us_VS_110_3_0_3_0_0%]>]
[<[%$TOPIC/c18k6c59_en-us_VS_110_3_0_3_0_1%](true)>]
[<[%$TOPIC/c18k6c59_en-us_VS_110_3_0_3_0_2%]([%$TOPIC/c18k6c59_en-us_VS_110_3_0_3_0_3%].None)>]
type Exception =  
    class 
        interface [%$TOPIC/c18k6c59_en-us_VS_110_3_0_3_0_4%] 
        interface [%$TOPIC/c18k6c59_en-us_VS_110_3_0_3_0_5%] 
    end

The Exception type exposes the following members.

Constructors
  NameDescription
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps ExceptionInitializes a new instance of the Exception class.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Exception(String)Initializes a new instance of the Exception class with a specified error message.
Protected method Exception(SerializationInfo, StreamingContext)Initializes a new instance of the Exception class with serialized data.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps 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.
Top
Properties
  NameDescription
Public property Supported by Portable Class Library Supported in .NET for Windows Store apps DataGets a collection of key/value pairs that provide additional user-defined information about the exception.
Public property Supported by Portable Class Library Supported in .NET for Windows Store apps HelpLinkGets or sets a link to the help file associated with this exception.
Public property Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps HResultGets or sets HRESULT, a coded numerical value that is assigned to a specific exception.
Public property Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps InnerExceptionGets the Exception instance that caused the current exception.
Public property Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps MessageGets a message that describes the current exception.
Public property Supported by Portable Class Library Supported in .NET for Windows Store apps SourceGets or sets the name of the application or the object that causes the error.
Public property Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps StackTraceGets a string representation of the immediate frames on the call stack.
Public property TargetSiteGets the method that throws the current exception.
Top
Methods
  NameDescription
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Equals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps FinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps GetBaseExceptionWhen overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps GetHashCodeServes as the default hash function. (Inherited from Object.)
Public method GetObjectDataWhen overridden in a derived class, sets the SerializationInfo with information about the exception.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps GetTypeGets 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.
Protected method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps ToStringCreates and returns a string representation of the current exception. (Overrides ObjectToString.)
Top
Events
  NameDescription
Protected event SerializeObjectStateOccurs when an exception is serialized to create an exception state object that contains serialized data about the exception.
Top
Remarks
NoteNote

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

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.

  • Usage errors. A usage error represents an error in program logic that can result in an exception. However, the error should be addressed not through exception handling but by modifying the faulty code. For example, the override of the ObjectEquals(Object) method in the following example assumes that the obj argument must always be non-null.

    Public Class Person
       Private _name As String 
    
       Public Property Name As String 
          Get 
             Return _name
          End Get 
          Set
             _name = value
          End Set 
       End Property 
    
       Public Overrides Function Equals(obj As Object) As Boolean 
          ' This implementation contains an error in program logic: 
          ' It assumes that the obj argument is not null. 
          Dim p As Person = CType(obj, Person)
          Return Me.Name.Equals(p.Name)
       End Function 
    End Class 
    
    Module Example
       Public Sub Main()
          Dim p1 As New Person()
          p1.Name = "John" 
          Dim p2 As Person = Nothing 
    
          ' The following throws a NullReferenceException.
          Console.WriteLine("p1 = p2: {0}", p1.Equals(p2))   
       End Sub 
    End Module
    using System;
    
    public class Person
    {
       private string _name;
    
       public string Name 
       {
          get { return _name; } 
          set { _name = value; }
       }
    
       public override int GetHashCode()
       {
          return this.Name.GetHashCode();  
       }  
    
       public override bool Equals(object obj)
       {
          // This implementation contains an error in program logic: 
          // It assumes that the obj argument is not null.
          Person p = (Person) obj;
          return this.Name.Equals(p.Name);
       }
    }
    
    public class Example
    {
       public static void Main()
       {
          Person p1 = new Person();
          p1.Name = "John";
          Person p2 = null; 
    
          // The following throws a NullReferenceException.
          Console.WriteLine("p1 = p2: {0}", p1.Equals(p2));   
       }
    }

    The NullReferenceException exception that results when obj is can be eliminated by modifying the source code to explicitly test for null before calling the ObjectEquals override and then re-compiling. The following example contains the corrected source code that handles a argument.

    Public Class Person
       Private _name As String 
    
       Public Property Name As String 
          Get 
             Return _name
          End Get 
          Set
             _name = value
          End Set 
       End Property 
    
       Public Overrides Function Equals(obj As Object) As Boolean 
          ' This implementation handles a null obj argument. 
          Dim p As Person = TryCast(obj, Person)
          If p Is Nothing Then  
             Return False 
          Else 
             Return Me.Name.Equals(p.Name)
          End If 
       End Function 
    End Class 
    
    Module Example
       Public Sub Main()
          Dim p1 As New Person()
          p1.Name = "John" 
          Dim p2 As Person = Nothing
    
          Console.WriteLine("p1 = p2: {0}", p1.Equals(p2))   
       End Sub 
    End Module 
    ' The example displays the following output: 
    '       p1 = p2: False
    using System;
    
    public class Person
    {
       private string _name;
    
       public string Name 
       {
          get { return _name; } 
          set { _name = value; }
       }
    
       public override int GetHashCode()
       {
          return this.Name.GetHashCode();  
       }  
    
       public override bool Equals(object obj)
       {
           // This implementation handles a null obj argument.
           Person p = obj as Person; 
           if (p == null) 
              return false;
           else 
              return this.Name.Equals(p.Name);
       }
    }
    
    public class Example
    {
       public static void Main()
       {
          Person p1 = new Person();
          p1.Name = "John";
          Person p2 = null; 
    
          Console.WriteLine("p1 = p2: {0}", p1.Equals(p2));   
       }
    }
    // The example displays the following output: 
    //        p1 = p2: False

    Instead of using exception handling for usage errors, you can use the DebugAssert method to identify usage errors in debug builds, and the TraceAssert method to identify usage errors in both debug and release builds. For more information, see Assertions in Managed Code.

  • Program errors. A program error is a run-time error that cannot necessarily be avoided by writing bug-free code.

    In some cases, a program error may reflect an expected or routine error condition. In this case, you may want to avoid using exception handling to deal with the program error and instead retry the operation. For example, if the user is expected to input a date in a particular format, you can parse the date string by calling the DateTimeTryParseExact method, which returns a Boolean value that indicates whether the parse operation succeeded, instead of using the DateTimeParseExact method, which throws a FormatException exception if the date string cannot be converted to a DateTime value. Similarly, if a user tries to open a file that does not exist, you can first call the FileExists method to check whether the file exists and, if it does not, prompt the user whether he or she wants to create it.

    In other cases, a program error reflects an unexpected error condition that can be handled in your code. For example, even if you've checked to ensure that a file exists, it may be deleted before you can open it, or it may be corrupted. In that case, trying to open the file by instantiating a StreamReader object or calling the Open method may throw a FileNotFoundException exception. In these cases, you should use exception handling to recover from the error.

  • System failures. A system failure is a run-time error that cannot be handled programmatically in a meaningful way. For example, any method can throw an OutOfMemoryException exception if the common language runtime is unable to allocate additional memory. Ordinarily, system failures are not handled by using exception handling. Instead, you may be able to use an event such as AppDomainUnhandledException and call the EnvironmentFailFast method to log exception information and notify the user of the failure before the application terminates.

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:

  • Human-readable text that describes the error. When an exception occurs, the runtime makes a text message available 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. For more information, see the Message property.

  • 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 the error occurs in the code. The stack trace lists all the called methods and the line numbers in the source file where the calls are made.

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: 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 about why the exception occurred, the 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 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, in some cases, such as when you're developing a class library, it's reasonable to throw an exception if a method argument is invalid, because you expect your method to be called with valid parameters. An invalid method argument, if it is not the result of a usage error, 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. Nor should you use exceptions to handle usage errors. Instead, use assertions to identify and correct usage errors.

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:

  • You are throwing an exception that is caused by a usage error (that is, by an error in program logic made by the developer who is calling your method). Typically, you would throw an exception such as ArgumentException, ArgumentNullException, InvalidOperationException, or NotSupportedException. The string you supply to the exception object's constructor when instantiating the exception object should describe the error so that the developer can fix it. For more information, see the Message property.

  • You are handling an error that can be communicated to the caller with an existing .NET Framework exception. You should throw the most derived exception possible. For example, if a method requires an argument to be a valid member of an enumeration type, you should throw an InvalidEnumArgumentException (the most derived class) rather than an ArgumentException.

The following table lists common exception types and the conditions under which you would throw them.

Exception

Condition

ArgumentException

A non-null argument that is passed to a method is invalid.

ArgumentNullException

An argument that is passed to a method is .

ArgumentOutOfRangeException

An argument is outside the range of valid values.

DirectoryNotFoundException

Part of a directory path is not valid.

DivideByZeroException

The denominator in an integer or Decimal division operation is zero.

DriveNotFoundException

A drive is unavailable or does not exist.

FileNotFoundException

A file does not exist.

FormatException

A value is not in an appropriate format to be converted from a string by a conversion method such as Parse.

IndexOutOfRangeException

An index is outside the bounds of an array or collection.

InvalidOperationException

A method call is invalid in an object's current state.

KeyNotFoundException

The specified key for accessing a member in a collection cannot be found.

NotImplementedException

A method or operation is not implemented.

NotSupportedException

A method or operation is not supported.

ObjectDisposedException

An operation is performed on an object that has been disposed.

OverflowException

An arithmetic, casting, or conversion operation results in an overflow.

PathTooLongException

A path or file name exceeds the maximum system-defined length.

PlatformNotSupportedException

The operation is not supported on the current platform.

RankException

An array with the wrong number of dimensions is passed to a method.

TimeoutException

The time interval allotted to an operation has expired.

UriFormatException

An invalid Uniform Resource Identifier (URI) is used.

Implementing custom exceptions

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

  • When the exception reflects a unique program error that cannot be mapped to an existing .NET Framework exception.

  • When the exception requires handling that is different from the handling that is appropriate for an existing .NET Framework exception, or the exception must be disambiguated from a similar exception. For example, if you throw an ArgumentOutOfRangeException exception when parsing the numeric representation of a string that is out of range of the target integral type, you would not want to use the same exception for an error that results from the caller not supplying the appropriate constrained values when calling the method.

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:

  1. Define a class that inherits from Exception. If necessary, 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.

  2. If necessary, override any inherited members whose functionality you want to change or modify. Note that most existing derived classes of Exception do not override the behavior of inherited members.

  3. 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.

  4. 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), which is 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 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 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.

Imports System.Runtime.Serialization

<Serializable()> _
Public Class NotPrimeException : Inherits Exception
   Private notAPrime As Integer 

   Protected Sub New()
      MyBase.New()
   End Sub 

   Public Sub New(value As Integer)
      MyBase.New(String.Format("{0} is not a prime number.", value))
      notAPrime = value
   End Sub 

   Public Sub New(value As Integer, message As String)
      MyBase.New(message)
      notAPrime = value
   End Sub 

   Public Sub New(value As Integer, message As String, innerException As Exception)
      MyBase.New(message, innerException)
      notAPrime = value
   End Sub 

   Protected Sub New(info As SerializationInfo,
                     context As StreamingContext)
      MyBase.New(info, context)
   End Sub 

   Public ReadOnly Property NonPrime As Integer 
      Get 
         Return notAPrime
      End Get 
   End Property 
End Class
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.

Imports System.Collections.Generic

<Serializable()> Public Class PrimeNumberGenerator
   Private Const START As Integer = 2
   Private maxUpperBound As Integer = 10000000
   Private upperBound As Integer 
   Private primeTable() As Boolean 
   Private primes As New List(Of Integer)

   Public Sub New(upperBound As Integer)
      If upperBound > maxUpperBound Then 
         Dim message As String = String.Format(
             "{0} exceeds the maximum upper bound of {1}.",
             upperBound, maxUpperBound)
         Throw New ArgumentOutOfRangeException(message)
      End If 
      Me.upperBound = upperBound
      ' Create array and mark 0, 1 as not prime (True). 
      ReDim primeTable(upperBound)
      primeTable(0) = True
      primeTable(1) = True 

      ' Use Sieve of Eratosthenes to determine prime numbers. 
      For ctr As Integer = START To CInt(Math.Ceiling(Math.Sqrt(upperBound)))
         If primeTable(ctr) Then Continue For 

         For multiplier As Integer = ctr To CInt(upperBound \ ctr)
            If ctr * multiplier <= upperBound Then primeTable(ctr * multiplier) = True 
         Next 
      Next 
      ' Populate array with prime number information. 
      Dim index As Integer = START
      Do While index <> -1
         index = Array.FindIndex(primeTable, index, Function(flag)
                                                       Return Not flag
                                                    End Function)
         If index >= 1 Then
            primes.Add(index)
            index += 1
         End If 
      Loop 
   End Sub 

   Public Function GetAllPrimes() As Integer()
      Return primes.ToArray()
   End Function 

   Public Function GetPrimesFrom(prime As Integer) As Integer()
      Dim start As Integer = primes.FindIndex(Function(value)
                                                 Return value = prime
                                              End Function)
      If start < 0 Then 
         Throw New NotPrimeException(prime, String.Format("{0} is not a prime number.", prime))
      Else 
         Return primes.FindAll(Function(value)
                                  Return value >= prime
                               End Function).ToArray()
      End If 
   End Function 
End Class
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.

Imports System.Reflection

Module Example
   Sub Main()
      Dim limit As Integer = 10000000
      Dim primes As New PrimeNumberGenerator(limit)
      Dim start As Integer = 1000001
      Try 
         Dim values() As Integer = primes.GetPrimesFrom(start)
         Console.WriteLine("There are {0} prime numbers from {1} to {2}",
                           start, limit)
      Catch e As NotPrimeException
         Console.WriteLine("{0} is not prime", e.NonPrime)
         Console.WriteLine(e)
         Console.WriteLine("--------")
      End Try 

      Dim domain As AppDomain = AppDomain.CreateDomain("Domain2")
      Dim gen As PrimeNumberGenerator = domain.CreateInstanceAndUnwrap(
                                        GetType(Example).Assembly.FullName,
                                        "PrimeNumberGenerator", True,
                                        BindingFlags.Default, Nothing,
                                        {1000000}, Nothing, Nothing)
      Try
         start = 100
         Console.WriteLine(gen.GetPrimesFrom(start))
      Catch e As NotPrimeException
         Console.WriteLine("{0} is not prime", e.NonPrime)
         Console.WriteLine(e)
         Console.WriteLine("--------")
      End Try 
   End Sub 
End Module 
' The example displays the following output: 
'      1000001 is not prime 
'      NotPrimeException: 1000001 is not a prime number. 
'         at PrimeNumberGenerator.GetPrimesFrom(Int32 prime) 
'         at Example.Main() 
'      -------- 
'      100 is not prime 
'      NotPrimeException: 100 is not a prime number. 
'         at PrimeNumberGenerator.GetPrimesFrom(Int32 prime) 
'         at Example.Main() 
'      --------
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("--------");
      }
   }
}

Windows Runtime and .NET Framework 4.5.1

In .NET for Windows Store apps for Windows 8, some exception information is typically lost when an exception is propagated through non-.NET Framework stack frames. Starting with the .NET Framework 4.5.1 and Windows 8.1, 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.

Examples

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.

Imports System

Class ExceptionTestClass

   Public Shared Sub Main()
      Dim x As Integer = 0
      Try 
         Dim y As Integer = 100 / x
      Catch e As ArithmeticException
         Console.WriteLine("ArithmeticException Handler: {0}", e.ToString())
      Catch e As Exception
         Console.WriteLine("Generic Exception Handler: {0}", e.ToString())
      End Try 
   End Sub 'Main
End Class 'ExceptionTestClass
' 
'This code example produces the following results: 
' 
'ArithmeticException Handler: System.OverflowException: Arithmetic operation resulted in an overflow. 
'   at ExceptionTestClass.Main() 
'
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()

*/
using namespace System;
int main()
{
    int x = 0;
    try
    {
        int y = 100 / x;
    }
    catch ( ArithmeticException^ e ) 
    {
        Console::WriteLine( "ArithmeticException Handler: {0}", e );
    }
    catch ( Exception^ e ) 
    {
        Console::WriteLine( "Generic Exception Handler: {0}", e );
    }
}
/*
This code example produces the following results:

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

*/
Version Information

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8
Platforms

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, 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.

Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Inheritance Hierarchy
SystemObject
  SystemException
     Microsoft.Build.BuildEngineInternalLoggerException
     Microsoft.Build.BuildEngineInvalidProjectFileException
     Microsoft.Build.BuildEngineInvalidToolsetDefinitionException
     Microsoft.Build.BuildEngineRemoteErrorException
     Microsoft.Build.ExceptionsBuildAbortedException
     Microsoft.Build.ExceptionsInternalLoggerException
     Microsoft.Build.ExceptionsInvalidProjectFileException
     Microsoft.Build.ExceptionsInvalidToolsetDefinitionException
     Microsoft.Build.FrameworkLoggerException
     Microsoft.CSharp.RuntimeBinderRuntimeBinderException
     Microsoft.CSharp.RuntimeBinderRuntimeBinderInternalCompilerException
     Microsoft.JScriptCmdLineException
     Microsoft.JScriptParserException
     Microsoft.VisualBasic.ApplicationServicesCantStartSingleInstanceException
     Microsoft.VisualBasic.ApplicationServicesNoStartupFormException
     Microsoft.VisualBasic.Compatibility.VB6WebClassContainingClassNotOptional
     Microsoft.VisualBasic.Compatibility.VB6WebClassCouldNotFindEvent
     Microsoft.VisualBasic.Compatibility.VB6WebClassNextItemCannotBeCurrentWebItem
     Microsoft.VisualBasic.Compatibility.VB6WebClassNextItemRespondNotFound
     Microsoft.VisualBasic.Compatibility.VB6WebClassUserWebClassNameNotOptional
     Microsoft.VisualBasic.Compatibility.VB6WebClassWebClassFileNameNotOptional
     Microsoft.VisualBasic.Compatibility.VB6WebClassWebItemNotValid
     Microsoft.VisualBasic.Compatibility.VB6WebItemAssociatedWebClassNotOptional
     Microsoft.VisualBasic.Compatibility.VB6WebItemClosingTagNotFound
     Microsoft.VisualBasic.Compatibility.VB6WebItemCouldNotLoadEmbeddedResource
     Microsoft.VisualBasic.Compatibility.VB6WebItemCouldNotLoadTemplateFile
     Microsoft.VisualBasic.Compatibility.VB6WebItemNameNotOptional
     Microsoft.VisualBasic.Compatibility.VB6WebItemNoTemplateSpecified
     Microsoft.VisualBasic.Compatibility.VB6WebItemTooManyNestedTags
     Microsoft.VisualBasic.Compatibility.VB6WebItemUnexpectedErrorReadingTemplateFile
     Microsoft.VisualBasic.CompilerServicesIncompleteInitialization
     Microsoft.VisualBasic.CompilerServicesInternalErrorException
     Microsoft.VisualBasic.FileIOMalformedLineException
     System.Activities.DynamicUpdateInstanceUpdateException
     System.Activities.ExpressionParserSourceExpressionException
     System.Activities.ExpressionsLambdaSerializationException
     System.ActivitiesInvalidWorkflowException
     System.Activities.Presentation.MetadataAttributeTableValidationException
     System.Activities.StatementsWorkflowTerminatedException
     System.ActivitiesVersionMismatchException
     System.ActivitiesWorkflowApplicationException
     System.AddIn.HostingAddInSegmentDirectoryNotFoundException
     System.AddIn.HostingInvalidPipelineStoreException
     SystemAggregateException
     SystemApplicationException
     System.ComponentModel.CompositionCompositionContractMismatchException
     System.ComponentModel.CompositionCompositionException
     System.ComponentModel.CompositionImportCardinalityMismatchException
     System.ComponentModel.Composition.PrimitivesComposablePartException
     System.ComponentModel.DataAnnotationsValidationException
     System.ComponentModel.DesignExceptionCollection
     System.Configuration.ProviderProviderException
     System.ConfigurationSettingsPropertyIsReadOnlyException
     System.ConfigurationSettingsPropertyNotFoundException
     System.ConfigurationSettingsPropertyWrongTypeException
     System.Data.LinqChangeConflictException
     System.Diagnostics.Eventing.ReaderEventLogException
     System.Diagnostics.TracingEventSourceException
     System.DirectoryServices.ActiveDirectoryActiveDirectoryObjectExistsException
     System.DirectoryServices.ActiveDirectoryActiveDirectoryObjectNotFoundException
     System.DirectoryServices.ActiveDirectoryActiveDirectoryOperationException
     System.DirectoryServices.ActiveDirectoryActiveDirectoryServerDownException
     System.DirectoryServices.ProtocolsDirectoryException
     System.IdentityModelAsynchronousOperationException
     System.IdentityModel.MetadataMetadataSerializationException
     System.IdentityModel.Protocols.WSTrustWSTrustSerializationException
     System.IdentityModelRequestException
     System.IdentityModel.SelectorsCardSpaceException
     System.IdentityModel.SelectorsIdentityValidationException
     System.IdentityModel.SelectorsPolicyValidationException
     System.IdentityModel.SelectorsServiceBusyException
     System.IdentityModel.SelectorsServiceNotStartedException
     System.IdentityModel.SelectorsStsCommunicationException
     System.IdentityModel.SelectorsUnsupportedPolicyOptionsException
     System.IdentityModel.SelectorsUntrustedRecipientException
     System.IdentityModel.SelectorsUserCancellationException
     System.IdentityModel.ServicesAsynchronousOperationException
     System.IdentityModel.ServicesFederatedAuthenticationSessionEndingException
     System.IdentityModel.ServicesFederationException
     System.IdentityModel.ServicesWSFederationMessageException
     SystemInvalidTimeZoneException
     System.IO.IsolatedStorageIsolatedStorageException
     System.IO.LogSequenceFullException
     System.Management.InstrumentationInstrumentationBaseException
     System.Management.InstrumentationWmiProviderInstallationException
     System.Net.HttpHttpRequestException
     System.Net.MailSmtpException
     System.Net.PeerToPeerPeerToPeerException
     System.Runtime.CompilerServicesRuntimeWrappedException
     System.Runtime.DurableInstancingInstancePersistenceException
     System.Runtime.Remoting.MetadataServicesSUDSGeneratorException
     System.Runtime.Remoting.MetadataServicesSUDSParserException
     System.Runtime.SerializationInvalidDataContractException
     System.Security.RightsManagementRightsManagementException
     System.ServiceModel.ChannelsInvalidChannelBindingException
     SystemSystemException
     System.ThreadingBarrierPostPhaseException
     System.ThreadingLockRecursionException
     System.Threading.TasksTaskSchedulerException
     SystemTimeZoneNotFoundException
     System.Web.Query.DynamicParseException
     System.Web.SecurityMembershipCreateUserException
     System.Web.SecurityMembershipPasswordException
     System.Web.UIViewStateException
     System.Web.UI.WebControlsEntityDataSourceValidationException
     System.Web.UI.WebControlsLinqDataSourceValidationException
     System.Windows.AutomationNoClickablePointException
     System.Windows.AutomationProxyAssemblyNotLoadedException
     System.Windows.ControlsPrintDialogException
     System.Windows.FormsAxHostInvalidActiveXStateException
     System.Windows.XpsXpsException
     System.Windows.XpsXpsWriterException
     System.Workflow.Activities.RulesRuleException
     System.Workflow.ComponentModel.CompilerWorkflowValidationFailedException
     System.Workflow.ComponentModel.SerializationWorkflowMarkupSerializationException
     System.Workflow.ComponentModelWorkflowTerminatedException
     System.Workflow.RuntimeWorkflowOwnershipException
     System.XamlXamlException