BCL mscorlib [00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 ] 1.0.5000.0 2.0.0.0 4.0.0.0 All public static members of this type are safe for multithreaded operations. No instance members are guaranteed to be thread safe. System.Object System.Runtime.InteropServices._Exception System.Runtime.Serialization.ISerializable System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None) System.Runtime.InteropServices.ComDefaultInterface(typeof(System.Runtime.InteropServices._Exception)) System.Runtime.InteropServices.ComVisible(true)

The following example demonstrates a catch block that is defined to handle errors. This catch block also catches errors because derives from , and there is no catch block explicitly defined for 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()); } } }`

The output is

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

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 method in the following example assumes that the argument must always be non-null.

code reference: System.Exception.Class#4

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

code reference: System.Exception.Class#5

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 method, which returns a value that indicates whether the parse operation succeeded, instead of using the method, which throws a exception if the date string cannot be converted to a value. Similarly, if a user tries to open a file that does not exist, you can first call the 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 object or calling the method may throw a 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 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 and call the 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 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 property.

The state of the call stack when the exception was thrown. The 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 class includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: , , , , , , , and .

When a causal relationship exists between two or more exceptions, the 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 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 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 property can hold a URL (or URN) to a help file.

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

For a list of initial property values for an instance of the class, see the 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:

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 , , , or . 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 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 (the most derived class) rather than an .

## 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 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 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 class; they do not override the members of , nor do they define any unique members.

To define your own exception class:

Define a class that inherits from . If necessary, define any unique members needed by your class to provide additional information about the exception. For example, the class includes a property that specifies the name of the parameter whose argument caused the exception, and the property includes a property that indicates the time-out interval.

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

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

Define the constructors of your exception class. Typically, exception classes have one or more of the following constructors:

, which uses default values to initialize the properties of a new exception object.

, which initializes a new exception object with a specified error message.

, which initializes a new exception object with a specified error message and inner exception.

, 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 and 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 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 object that was thrown unless that exception was modified in a non-.NET Framework stack frame.

Represents errors that occur during application execution.

- Constructor
  1.0.5000.0
  2.0.0.0
  4.0.0.0

  This constructor initializes the property of the new instance to a system-supplied message that describes the error and takes into account the current system culture.

  All the derived classes should provide this default constructor. The following table shows the initial property values for an instance of .

  Property

  Value

  A null reference (Nothing in Visual Basic).

  A system-supplied localized description.

  Initializes a new instance of the class.

  0
- Constructor
  1.0.5000.0
  2.0.0.0
  4.0.0.0

  This constructor initializes the property of the new instance by using the parameter. If the parameter is null, this is the same as calling the constructor.

  The following table shows the initial property values for an instance of .

  Property

  Value

  A null reference (Nothing in Visual Basic).

  The error message string.

  Initializes a new instance of the class with a specified error message.

  The message that describes the error.
  0
- Constructor
  1.0.5000.0
  2.0.0.0
  4.0.0.0

  This constructor is called during deserialization to reconstitute the exception object transmitted over a stream. For more information, see [<topic://cpconSerialization>].

  Initializes a new instance of the class with serialized data.

  The that holds the serialized object data about the exception being thrown.
  The that contains contextual information about the source or destination.
- Constructor
  1.0.5000.0
  2.0.0.0
  4.0.0.0

  An exception that is thrown as a direct result of a previous exception should include a reference to the previous exception in the property. The property returns the same value that is passed into the constructor, or a null reference (Nothing in Visual Basic) if the property does not supply the inner exception value to the constructor.

  The following table shows the initial property values for an instance of .

  Property

  Value

  The inner exception reference.

  The error message string.

  Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception.

  The error message that explains the reason for the exception.
  The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.
  0
- Property
  2.0.0.0
  4.0.0.0
  System.Collections.IDictionary To be added.

  Use the object returned by the property to store and retrieve supplementary information relevant to the exception. The information is in the form of an arbitrary number of user-defined key/value pairs. The key component of each key/value pair is typically an identifying string, whereas the value component of the pair can be any type of object.

  ## Key/Value Pair Security

  The key/value pairs stored in the collection returned by the property are not secure. If your application calls a nested series of routines, and each routine contains exception handlers, the resulting call stack contains a hierarchy of those exception handlers. If a lower-level routine throws an exception, any upper-level exception handler in the call stack hierarchy can read and/or modify the key/value pairs stored in the collection by any other exception handler. This means you must guarantee that the information in the key/value pairs is not confidential and that your application will operate correctly if the information in the key/value pairs is corrupted.

  ## Key Conflicts

  A key conflict occurs when different exception handlers specify the same key to access a key/value pair. Use caution when developing your application because the consequence of a key conflict is that lower-level exception handlers can inadvertently communicate with higher-level exception handlers, and this communication might cause subtle program errors. However, if you are cautious you can use key conflicts to enhance your application.

  ## Avoiding Key Conflicts

  Avoid key conflicts by adopting a naming convention to generate unique keys for key/value pairs. For example, a naming convention might yield a key that consists of the period-delimited name of your application, the method that provides supplementary information for the pair, and a unique identifier.

  Suppose two applications, named Products and Suppliers, each has a method named Sales. The Sales method in the Products application provides the identification number (the stock keeping unit or SKU) of a product. The Sales method in the Suppliers application provides the identification number, or SID, of a supplier. Consequently, the naming convention for this example yields the keys, "Products.Sales.SKU" and "Suppliers.Sales.SID".

  ## Exploiting Key Conflicts

  Exploit key conflicts by using the presence of one or more special, prearranged keys to control processing. Suppose, in one scenario, the highest level exception handler in the call stack hierarchy catches all exceptions thrown by lower-level exception handlers. If a key/value pair with a special key exists, the high-level exception handler formats the remaining key/value pairs in the object in some nonstandard way; otherwise, the remaining key/value pairs are formatted in some normal manner.

  Now suppose, in another scenario, the exception handler at each level of the call stack hierarchy catches the exception thrown by the next lower-level exception handler. In addition, each exception handler knows the collection returned by the property contains a set of key/value pairs that can be accessed with a prearranged set of keys.

  Each exception handler uses the prearranged set of keys to update the value component of the corresponding key/value pair with information unique to that exception handler. After the update process is complete, the exception handler throws the exception to the next higher-level exception handler. Finally, the highest level exception handler accesses the key/value pairs and displays the consolidated update information from all the lower-level exception handlers.

  The , , and classes always return null for the value of the property.

  Gets a collection of key/value pairs that provide additional user-defined information about the exception.

- Method
  1.0.5000.0
  2.0.0.0
  4.0.0.0
  System.Exception

  The following example shows an implementation of the method.

  `public virtual Exception GetBaseException() { Exception inner = InnerException; Exception back = this; while (inner != null) { back = inner; inner = inner.InnerException; } return back; }`

  A chain of exceptions consists of a set of exceptions such that each exception in the chain was thrown as a direct result of the exception referenced in its InnerException property. For a given chain, there can be exactly one exception that is the root cause of all other exceptions in the chain. This exception is called the base exception and its InnerException property always contains a null reference.

  For all exceptions in a chain of exceptions, the GetBaseException method must return the same object (the base exception).

  Use the GetBaseException method when you want to find the root cause of an exception but do not need information about exceptions that may have occurred between the current exception and the first exception.

  When overridden in a derived class, returns the that is the root cause of one or more subsequent exceptions.

  The first exception thrown in a chain of exceptions. If the property of the current exception is a null reference (Nothing in Visual Basic), this property returns the current exception.

  0
- Method
  1.0.5000.0
  2.0.0.0
  4.0.0.0
  System.Void `` ``

  GetObjectData sets a with all the exception object data targeted for serialization. During deserialization, the exception is reconstituted from the SerializationInfo transmitted over the stream.

  When overridden in a derived class, sets the with information about the exception.

  The that holds the serialized object data about the exception being thrown. The that contains contextual information about the source or destination.
- Method
  2.0.0.0
  4.0.0.0
  System.Type

  The method exists to support the .NET Framework infrastructure, and internally invokes the fundamental method, .

  Gets the runtime type of the current instance.

  A object that represents the exact runtime type of the current instance.

- Property
  1.0.5000.0
  2.0.0.0
  4.0.0.0
  System.String To be added.

  The return value, which represents a help file, is a URN or URL. For example, the HelpLink value could be:

  "file:///C:/Applications/Bazzal/help.html#ErrorNum42"

  Gets or sets a link to the help file associated with this exception.

- Property
  1.0.5000.0
  2.0.0.0
  4.0.0.0
  System.Int32 To be added.

  HRESULT is a 32-bit value, divided into three different fields: a severity code, a facility code, and an error code. The severity code indicates whether the return value represents information, warning, or error. The facility code identifies the area of the system responsible for the error. The error code is a unique number that is assigned to represent the exception. Each exception is mapped to a distinct HRESULT. When managed code throws an exception, the runtime passes the HRESULT to the COM client. When unmanaged code returns an error, the HRESULT is converted to an exception, which is then thrown by the runtime. For information about HRESULT values and their corresponding .NET Framework exceptions, see How to: Map HRESULTs and Exceptions.

  Starting with the net_v45, the property's setter is protected, whereas its getter is public. In previous versions of the .NET Framework, both getter and setter are protected.

  Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

- Property
  1.0.5000.0
  2.0.0.0
  4.0.0.0
  System.Exception

  An instance of that describes the error that caused the current Exception.

  The following example demonstrates throwing and catching an Exception that references an inner Exception.

  `using System; public class MyAppException:ApplicationException { public MyAppException (String message) : base (message) {} public MyAppException (String message, Exception inner) : base(message,inner) {} } public class ExceptExample { public void ThrowInner () { throw new MyAppException("ExceptExample inner exception"); } public void CatchInner() { try { this.ThrowInner(); } catch (Exception e) { throw new MyAppException("Error caused by trying ThrowInner.",e); } } } public class Test { public static void Main() { ExceptExample testInstance = new ExceptExample(); try { testInstance.CatchInner(); } catch(Exception e) { Console.WriteLine ("In Main catch block. Caught: {0}", e.Message); Console.WriteLine ("Inner Exception is {0}",e.InnerException); } } }`

  The output is

  `In Main catch block. Caught: Error caused by trying ThrowInner. Inner Exception is MyAppException: ExceptExample inner exception at ExceptExample.ThrowInner() at ExceptExample.CatchInner()`

  When an exception is thrown as a direct result of a previous exception , the InnerException property of should contain a reference to .

  Use the InnerException property to obtain the set of exceptions that led to the current exception.

  You can create a new exception that catches an earlier exception. The code that handles the second exception can make use of the additional information from the earlier exception to handle the error more appropriately.

  Suppose that there is a function that reads a file and formats the data from that file. In this example, as the code tries to read the file, an is thrown. The function catches the and throws a . The could be saved in the property of the , enabling the code that catches the to examine what causes the initial error.

  The property, which holds a reference to the inner exception, is set upon initialization of the exception object.

  Gets the instance that caused the current exception.

  0
- Property
  1.0.5000.0
  2.0.0.0
  4.0.0.0
  System.String

  A that contains a detailed description of the error, or . This value is intended to be understood by humans.

  Error messages target the developer who is handling the exception. The text of the property should completely describe the error and, when possible, should also explain how to correct the error. Top-level exception handlers may display the message to end-users, so you should ensure that it is grammatically correct and that each sentence of the message ends with a period. Do not use question marks or exclamation points. If your application uses localized exception messages, you should ensure that they are accurately translated.

  Do not disclose sensitive information in exception messages without checking for the appropriate permissions.

  The value of the property is included in the information returned by .The property is set only when creating an . If no message was supplied to the constructor for the current instance, the system supplies a default message that is formatted using the current system culture.

  ## Windows Runtime and net_v451

  Starting with the net_v451 and win81, the fidelity of error messages from exceptions that are propagated from Windows Runtime types and members that are not part of the .NET Framework is improved. In particular, exception messages from Visual C++ component extensions (C++/CX) are now propagated back into .NET Framework objects.

  Gets a message that describes the current exception.

  0
- Event
  4.0.0.0
  System.EventHandler<System.Runtime.Serialization.SafeSerializationEventArgs>

  The exception state object implements the interface.

  When the event is subscribed to, the exception is deserialized and created as an empty exception. The exception's constructor is not run, and the exception state is also deserialized. The callback method of the exception state object is then notified so that it can push deserialized data into the empty exception.

  The event enables transparent exception types to serialize and deserialize exception data. Transparent code can execute commands within the bounds of the permission set it is operating within, but cannot execute, call, derive from, or contain critical code.

  If the event is not subscribed to, deserialization occurs as usual using the constructor.

  Typically, a handler for the event is added in the exception's constructor to provide for its serialization. But because the constructor is not executed when the event handler executes, serializing a deserialized exception can throw a exception when you try to deserialize the exception. To avoid this, you should also add the handler for the event in the method. See the Examples section for an illustration.

  Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

- Property
  1.0.5000.0
  2.0.0.0
  4.0.0.0
  System.String To be added.

  If is not set, the name of the assembly where the exception originated is returned.

  Gets or sets the name of the application or the object that causes the error.

- Property
  1.0.5000.0
  2.0.0.0
  4.0.0.0
  System.String

  A that describes the contents of the call stack.

  The execution stack keeps track of all the methods that are in execution at a given instant. A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs.

  The property returns the frames of the call stack that originate at the location where the exception was thrown. You can obtain information about additional frames in the call stack by creating a new instance of the class and using its method.

  The common language runtime (CLR) updates the stack trace whenever an exception is thrown in application code (by using the throw keyword). If the exception was rethrown in a method that is different than the method where it was originally thrown, the stack trace contains both the location in the method where the exception was originally thrown, and the location in the method where the exception was rethrown. If the exception is thrown, and later rethrown, in the same method, the stack trace only contains the location where the exception was rethrown and does not include the location where the exception was originally thrown.

  The property may not report as many method calls as expected because of code transformations, such as inlining, that occur during optimization.

  Gets a string representation of the immediate frames on the call stack.

  0
- Property
  1.0.5000.0
  2.0.0.0
  4.0.0.0
  System.Reflection.MethodBase To be added.

  If the method that throws this exception is not available and the stack trace is not a null reference (Nothing in Visual Basic), obtains the method from the stack trace. If the stack trace is a null reference, also returns a null reference.

  The property may not accurately report the name of the method in which an exception was thrown if the exception handler handles an exception across application domain boundaries.

  Gets the method that throws the current exception.

- Method
  1.0.5000.0
  2.0.0.0
  4.0.0.0
  System.String

  The following example causes an Exception and displays the result of calling on that Exception.

  `using System; public class MyClass {} public class ArgExceptionExample { public static void Main() { MyClass my = new MyClass(); string s = "sometext"; try { int i = s.CompareTo(my); } catch (Exception e) { Console.WriteLine("Error: {0}",e.ToString()); } } }`

  The output is

  `Error: System.ArgumentException: Object must be of type String. at System.String.CompareTo(Object value) at ArgExceptionExample.Main()`

  returns a representation of the current exception that is intended to be understood by humans. Where the exception contains culture-sensitive data, the string representation returned by ToString is required to take into account the current system culture. Although there are no exact requirements for the format of the returned string, it should attempt to reflect the value of the object as perceived by the user.

  The default implementation of obtains the name of the class that threw the current exception, the message, the result of calling on the inner exception, and the result of calling . If any of these members is null, its value is not included in the returned string.

  If there is no error message or if it is an empty string (""), then no error message is returned. The name of the inner exception and the stack trace are returned only if they are not null.

  This method overrides .

  Creates and returns a string representation of the current exception.

  A string representation of the current exception.

  0
0