[Serializable] |
The common language runtime provides an exception handling model that is based on the representation of exceptions as objects, and the separation of program code and exception handling code into try blocks and catch blocks, respectively. There can be one or more catch blocks, each designed to handle a particular type of exception, or one block designed to catch a more specific exception than another block.
If an application handles exceptions that occur during the execution of a block of application code, the code must be placed within a try statement. Application code within a try statement is a try block. Application code that handles exceptions thrown by a try block is placed within a catch statement, and is called a catch block. Zero or more catch blocks are associated with a try block, and each catch block includes a type filter that determines the types of exceptions it handles.
When an exception occurs in a try block, the system searches the associated catch blocks in the order they appear in application code, until it locates a catch block that handles the exception. A catch block handles an exception of type T if the type filter of the catch block specifies T or any type that T derives from. The system stops searching after it finds the first catch block that handles the exception. For this reason, in application code, a catch block that handles a type must be specified before a catch block that handles its base types, as demonstrated in the example that follows this section. A catch block that handles System.Exception is specified last.
If none of the catch blocks associated with the current try block handle the exception, and the current try block is nested within other try blocks in the current call, the catch blocks associated with the next enclosing try block are searched. If no catch block for the exception is found, the system searches previous nesting levels in the current call. If no catch block for the exception is found in the current call, the exception is passed up the call stack, and the previous stack frame is searched for a catch block that handles the exception. The search of the call stack continues until the exception is handled or until no more frames exist on the call stack. If the top of the call stack is reached without finding a catch block that handles the exception, the default exception handler handles it and the application terminates.
Exception types support the following features:
Two categories of exceptions exist under the base class Exception:
Exception includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: Exception.StackTrace, Exception.InnerException, Exception.Message, Exception.HelpLink, Exception.HResult, Exception.Source, and Exception.TargetSite.
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.
The error message string passed to the constructor during the creation of the exception object should be localized, and can be supplied from a resource file using the ResourceManager. For more information on localized resources, see the System.Resources namespace overview and .
To provide the user with extensive information concerning why the exception occurred, the Exception.HelpLink property can hold a URL (or URN) to a help file.
Exception uses the HRESULT COR_E_EXCEPTION, which has the value 0x80131500.
For a list of initial property values for an instance of Exception, see the constructors.
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 C# code has the following output:
ArithmeticException Handler:
System.DivideByZeroException: Attempted to divide by zero. at
ExceptionTestClass.Main()
The Visual Basic code has the following output:
ArithmeticException Handler:
System.OverflowException: Exception of type System.OverflowException was thrown.
at ExceptionTestClass.Main()
ctor #1 | Overloaded:.ctor() Default constructor. This constructor is called by derived class constructors to initialize state in this type.Initializes a new instance of the Exception class. |
ctor #2 | Overloaded:.ctor(string message) Initializes a new instance of the Exception class with a specified error message. |
ctor #4 | Overloaded:.ctor(string message, Exception innerException) 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. |
HelpLink | Read-write Gets or sets a link to the help file associated with this exception. |
InnerException | Read-only Gets the Exception instance that caused the current exception. |
Message | Read-only Gets a message that describes the current exception. |
Source | Read-write Gets or sets the name of the application or the object that causes the error. |
StackTrace | Read-only Gets a string representation of the frames on the call stack at the time the current exception was thrown. |
TargetSite | Read-only Gets the method that throws the current exception. |
Equals (inherited from System.Object) |
See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. |
GetBaseException | When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. |
GetHashCode (inherited from System.Object) |
See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. |
GetObjectData | When overridden in a derived class, sets the SerializationInfo with information about the exception. |
GetType (inherited from System.Object) |
See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
ToString | Overridden: Creates and returns a string representation of the current exception. |
ctor #3 | Overloaded:.ctor(SerializationInfo info, StreamingContext context) Initializes a new instance of the Exception class with serialized data. |
HResult | Read-write Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. |
Finalize (inherited from System.Object) |
See base class member description: System.Object.Finalize Derived from System.Object, the primary base class for all objects. |
MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
public Exception(); |
All the derived classes should provide this default constructor. The following table shows the initial property values for an instance of Exception.
Property | Value |
---|---|
Exception.InnerException | A null reference ( not set or empty in Visual Basic). (Visual Basic not implemented in the shared source CLI) |
Exception.Message | A system-supplied localized description. |
public Exception( |
message
The following table shows the initial property values for an instance of Exception.
Property | Value |
---|---|
Exception.InnerException | A null reference ( not set or empty in Visual Basic). (Visual Basic not implemented in the shared source CLI) |
Exception.Message | The error message string. |
protected Exception( |
info
context
Exception Type | Condition |
---|---|
ArgumentNullException | The info parameter is null. |
SerializationException | The class name is null or Exception.HResult is zero (0). |
public Exception(string message, Exception innerException( |
message
innerException
The following table shows the initial property values for an instance of Exception.
Property | Value |
---|---|
Exception.InnerException | The inner exception reference. |
Exception.Message | The error message string. |
public virtual string HelpLink {get; set;}
|
"file:///C:/Applications/Bazzal/help.html#ErrorNum42"
protected int HResult {get; set;}
|
public Exception InnerException {get;}
|
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 IOException is thrown. The function catches the IOException and throws a FileNotFoundException. The IOException could be saved in the Exception.InnerException property of the FileNotFoundException, enabling the code that catches the FileNotFoundException to examine what causes the initial error.
The Exception.InnerException property, which holds a reference to the inner exception, is set upon initialization of the exception object.
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); } } }
This code has the following output:
In Main
catch block. Caught: Error caused by trying ThrowInner. Inner Exception is
MyAppException: ExceptExample inner exception at ExceptExample.ThrowInner() at
ExceptExample.CatchInner()
public virtual string Message {get;}
|
The Message property is set only when creating an Exception. 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.
The error message should be localized.
public virtual string Source {get; set;}
|
public virtual string StackTrace {get;}
|
StackTrace may not report as many method calls as expected, due to code transformations, such as inlining, that occur during optimization.
By default, the stack trace is captured immediately before an exception object is thrown. Use Environment.StackTrace to get stack trace information when no exception is being thrown.
public MethodBase TargetSite {get;}
|
~Exception(); |
public virtual Exception GetBaseException(); |
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.
public virtual int GetHashCode(); |
public virtual void GetObjectData( |
info
context
Exception Type | Condition |
---|---|
ArgumentNullException | The info parameter is a null reference (not set or empty). |
public Type GetType(); |
protected object MemberwiseClone(); |
public override string ToString(); |
The default implementation of Exception.ToString obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment.StackTrace. If any of these members is a null reference (not set or empty), 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 a null reference.
This method overrides Object.ToString.
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()); } } }
This code has the following output:
Error:
System.ArgumentException: Object must be of type String. at
System.String.CompareTo(Object value) at ArgExceptionExample.Main()