System.Exception Class

public class Exception

Base Types

Object
  Exception

Assembly

mscorlib

Library

BCL

Summary

Represents errors that occur during application execution.

Description

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.

[Note: For a description of the exception handling model, see Partition I of the CLI Specification.]

[Note: If an application handles exceptions that occur during the execution of a block of application code, the code is required to 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 Exception is specified last.

If the catch blocks associated with the current try block do not 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 there are no more frames in 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 types support the following features:

The Base Class Library provides two types that inherit directly from Exception :

[Note: Most user-defined exceptions derive from ApplicationException. For more information, see ApplicationException and SystemException .]

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.

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

See Also

System Namespace

Members

Exception Constructors

Exception() Constructor
Exception(System.String) Constructor
Exception(System.String, System.Exception) Constructor

Exception Methods

Exception.GetBaseException Method
Exception.ToString Method

Exception Properties

Exception.InnerException Property
Exception.Message Property
Exception.StackTrace Property


Exception() Constructor

public Exception();

Summary

Constructs and initializes a new instance of the Exception class.

Description

This constructor initializes the System.Exception.Message property of the new instance to a system-supplied message that describes the error and takes into account the current system culture. The System.Exception.InnerException property is initialized to null and the System.Exception.StackTrace property is initialized to System.String.Empty .

See Also

System.Exception Class, System Namespace

Exception(System.String) Constructor

public Exception(string message);

Summary

Constructs a new instance of the Exception class.

Parameters

message
A String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.

Description

This constructor initializes the System.Exception.Message property of the new instance using message. If message is null , the System.Exception.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.Exception.InnerException property is initialized to null and the System.Exception.StackTrace property is initialized to System.String.Empty.

See Also

System.Exception Class, System Namespace

Exception(System.String, System.Exception) Constructor

public Exception(string message, Exception innerException);

Summary

Constructs a new instance of the Exception class.

Parameters

message
A String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException .

Description

This constructor initializes the System.Exception.Message property of the new instance using message, and the System.Exception.InnerException property using innerException. If message is null , the System.Exception.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments.

The System.Exception.StackTrace property is initialized to System.String.Empty.

See Also

System.Exception Class, System Namespace

Exception.GetBaseException Method

public virtual Exception GetBaseException();

Summary

Returns the Exception that is the root cause of one or more subsequent Exceptions.

Return Value

Returns the first Exception thrown in a chain of Exceptions. If the System.Exception.InnerException property of the current Exception is null , returns the current Exception.

Description

[Note: 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 System.Exception.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 baseexception and its System.Exception.InnerException property always contains a null reference.]

[Behaviors: For all Exceptions in a chain of Exceptions, the System.Exception.GetBaseException method is required to return the same object (the base exception ).]

[Overrides: The System.Exception.GetBaseException method is overridden in classes that require control over the exception content or format. ]

[Usage: Use the System.Exception.GetBaseException method when you want to find the root cause of an Exception but do not need information about Exceptions that might have occurred between the current Exception and the first Exception. ]

Example

The following example shows an implementation of the System.Exception.GetBaseException method.

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

See Also

System.Exception Class, System Namespace

Exception.ToString Method

public override string ToString();

Summary

Creates and returns a String representation of the current Exception.

Return Value

A String representation of the current Exception.

Description

[Behaviors: System.Exception.ToString 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 System.Exception.ToString is required to take into account the current system culture. [Note: Although there are no exact requirements for the format of the returned string, it should as much as possible reflect the value of the object as perceived by the user.]

[Note: This method overrides System.Object.ToString.]

]

[Default: The System.Exception.ToString implementation obtains the fully qualified name of the current Exception, the message, the result of calling System.Exception.ToString on the inner exception, and the result of calling System.Environment.StackTrace. If any of these members is null or equal to System.String.Empty , its value is not included in the returned string.

]

[Overrides: It is recommended, but not required, that System.Exception.ToString be overridden to return information about members declared in the derived class. For example, the ArgumentException class overrides System.Exception.ToString so that it returns the value of the System.ArgumentException.ParamName property, if that value is not null .

]

[Usage: Use the System.Exception.ToString method to obtain a string representation of an Exception.

]

Example

The following example causes an Exception and displays the result of calling System.Exception.ToString 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()
 

See Also

System.Exception Class, System Namespace

Exception.InnerException Property

public Exception InnerException { get; }

Summary

Gets the Exception instance that caused the current Exception.

Property Value

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

Description

This property is read-only.

[Note: When an Exception X is thrown as a direct result of a previous exception Y , the System.Exception.InnerException property of X should contain a reference to Y .]

The System.Exception.InnerException property returns the same value as was passed into the constructor, or null if the inner exception value was not supplied to the constructor.

[Note: Using the System.Exception.InnerException property, you can obtain the set of Exceptions that led to the current Exception. System.Exception.GetBaseException includes an example that demonstrates this procedure.]

Example

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

See Also

System.Exception Class, System Namespace

Exception.Message Property

public virtual string Message { get; }

Summary

Gets a String containing a message that describes the current Exception.

Property Value

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

Description

[Note: The text of System.Exception.Message should completely describe the error and should, when possible, explain how to correct it.

The value of the System.Exception.Message property is included in the information returned by System.Exception.ToString .

]

This property is read-only.

[Behaviors: The System.Exception.Message property is set only when creating an Exception instance.

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.

]

[Overrides: The System.Exception.Message property is overridden in classes that require control over message content or format.

]

[Usage: Application code typically accesses this property when there is a need to display information about an exception that has been caught.

]

See Also

System.Exception Class, System Namespace

Exception.StackTrace Property

public virtual string StackTrace { get; }

Summary

Gets a String representation of the frames on the call stack at the time the current Exception was thrown.

Property Value

A String that describes the contents of the call stack.

Description

[Note: System.Exception.StackTrace might not report as many method calls as expected, due to code transformations, such as inlining, that occur during optimization.]

This property is read-only.

[Behaviors: The format of the information returned by this property is required to be identical to the format of the information returned by System.Environment.StackTrace .

]

[Overrides: The System.Exception.StackTrace property is overridden in classes that require control over the stack trace content or format.

]

[Usage: Use the System.Exception.StackTrace property to obtain a string representation of the contents of the call stack at the time the exception was thrown.

]

See Also

System.Exception Class, System Namespace