共用方式為


Exception Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Represents errors that occur during application execution.

Inheritance Hierarchy

System.Object
  System.Exception
    More...

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
<ClassInterfaceAttribute(ClassInterfaceType.None)> _
<ComVisibleAttribute(True)> _
Public Class Exception
[ClassInterfaceAttribute(ClassInterfaceType.None)]
[ComVisibleAttribute(true)]
public class Exception

The Exception type exposes the following members.

Constructors

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Exception() Initializes a new instance of the Exception class.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Exception(String) Initializes a new instance of the Exception class with a specified error message.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 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

  Name Description
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Data Gets a collection of key/value pairs that provide additional user-defined information about the exception.
Protected propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 HResult Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 InnerException Gets the Exception instance that caused the current exception.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 Message Gets a message that describes the current exception.
Public propertySupported by Silverlight for Windows PhoneSupported by Xbox 360 StackTrace Gets a string representation of the frames on the call stack at the time the current exception was thrown.

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetBaseException When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetType Gets the runtime type of the current instance.
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString Creates and returns a string representation of the current exception. (Overrides Object.ToString().)

Top

Remarks

This class is the base class for all exceptions. When an error occurs, either the system or the currently executing application reports it by throwing an exception containing information about the error. Once thrown, an exception is handled by the application or by the default exception handler.

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, 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 Type Features

Exception types support the following features:

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

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

Exception Type Categories

Two categories of exceptions exist under the base class Exception:

  • The pre-defined common language runtime exception classes derived from SystemException.

Exception Class Properties

Exception 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, HResult, 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 in the Data property.

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.

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 Exception constructors.

Performance Considerations

A significant amount of system resources and execution time are used when you throw or handle an exception. Throw exceptions only to handle truly extraordinary conditions, not to handle predictable events or flow control. For example, your application can reasonably throw an exception if a method argument is invalid because you expect to call your method with valid parameters. An invalid method argument means 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. In such a case, provide a retry mechanism so users can enter valid input.

Throw exceptions only for extraordinary conditions, then catch exceptions in a general purpose exception handler that applies to the majority of your application, not a handler that applies to a specific exception. The rationale for this approach is that most errors can be handled by validation and error handling code in proximity to the error; no exception needs to be thrown or caught. The general purpose exception handler catches truly unexpected exceptions thrown anywhere in the application.

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, then continue processing.

Examples

The following code 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.


Class Example

   Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      Dim x As Integer = 0
      Try
         Dim y As Integer = 100 / x
      Catch e As ArithmeticException
         outputBlock.Text += String.Format("ArithmeticException Handler: {0}", e.ToString()) & vbCrLf
      Catch e As Exception
         outputBlock.Text += String.Format("Generic Exception Handler: {0}", e.ToString()) & vbCrLf
      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 Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      int x = 0;
      try
      {
         int y = 100 / x;
      }
      catch (ArithmeticException e)
      {
         outputBlock.Text += String.Format("ArithmeticException Handler: {0}", e.ToString()) + "\n";
      }
      catch (Exception e)
      {
         outputBlock.Text += String.Format("Generic Exception Handler: {0}", e.ToString()) + "\n";
      }
   }
}
/*
This code example produces the following results:

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

*/

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

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.

See Also

Reference

Other Resources

Inheritance Hierarchy

System.Object
  System.Exception
    Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
    Microsoft.CSharp.RuntimeBinder.RuntimeBinderInternalCompilerException
    Microsoft.VisualBasic.CompilerServices.IncompleteInitialization
    Microsoft.VisualBasic.CompilerServices.InternalErrorException
    System.AggregateException
    System.ComponentModel.Composition.CompositionContractMismatchException
    System.ComponentModel.Composition.CompositionException
    System.ComponentModel.Composition.ImportCardinalityMismatchException
    System.ComponentModel.Composition.Primitives.ComposablePartException
    System.ComponentModel.DataAnnotations.ValidationException
    System.ComponentModel.InvalidEnumArgumentException
    System.InvalidTimeZoneException
    System.IO.IsolatedStorage.IsolatedStorageException
    System.Net.Sockets.SocketException
    System.Reflection.TargetException
    System.Reflection.TargetInvocationException
    System.Reflection.TargetParameterCountException
    System.Runtime.Serialization.InvalidDataContractException
    System.SystemException
    System.Threading.Tasks.TaskSchedulerException
    System.Windows.Automation.ElementNotAvailableException
    System.Windows.Automation.ElementNotEnabledException
    System.Windows.LayoutCycleException
    System.Windows.Messaging.ListenFailedException
    System.Windows.Messaging.SendFailedException