Exception Exception Exception Exception Class

定义

表示在应用程序执行过程中发生的错误。Represents errors that occur during application execution.

public ref class Exception : System::Runtime::InteropServices::_Exception, System::Runtime::Serialization::ISerializable
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDual)]
[System.Serializable]
public class Exception : System.Runtime.InteropServices._Exception, System.Runtime.Serialization.ISerializable
type Exception = class
    interface ISerializable
    interface _Exception
Public Class Exception
Implements _Exception, ISerializable
继承
ExceptionExceptionExceptionException
派生
属性
实现

示例

下面的示例演示catch了定义用于处理ArithmeticException错误的块。The following example demonstrates a catch block that is defined to handle ArithmeticException errors. catch块还会DivideByZeroException捕获错误, DivideByZeroException因为派生ArithmeticException自, 并且没有catch显式定义错误的DivideByZeroException块。This catch block also catches DivideByZeroException errors, because DivideByZeroException derives from ArithmeticException and there is no catch block explicitly defined for DivideByZeroException errors.

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()
 
*/
using System;

class ExceptionTestClass 
{
   public static void Main() 
   {
      int x = 0;
      try 
      {
         int y = 100 / x;
      }
      catch (ArithmeticException e) 
      {
         Console.WriteLine($"ArithmeticException Handler: {e}");
      }
      catch (Exception e) 
      {
         Console.WriteLine($"Generic Exception Handler: {e}");
      }
   }	
}
/*
This code example produces the following results:

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

*/
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()
'

注解

此类是所有异常的基类。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 块 Try/catch blocks
异常类型功能 Exception type features
异常类属性 Exception class properties
性能注意事项 Performance considerations
重新引发异常 Re-throwing an exception
选择标准异常 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. 例如, 以下示例中Object.Equals(Object)方法的重写假定obj参数必须始终为非 null。For example, the override of the Object.Equals(Object) method in the following example assumes that the obj argument must always be non-null.

    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));   
       }
    }
    
    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
    

    null Object.EqualsNullReferenceException 可以通过在调用重写然后重新编译之前,通过修改源代码来显式测试null,从而导致obj出现的异常。The NullReferenceException exception that results when obj is null can be eliminated by modifying the source code to explicitly test for null before calling the Object.Equals override and then re-compiling. 下面的示例包含处理null参数的正确源代码。The following example contains the corrected source code that handles a null argument.

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

    您可以使用Debug.Assert方法来识别调试生成中的使用错误, Trace.Assert并使用方法标识调试和发布版本中的使用错误, 而不是使用异常处理来处理使用错误。Instead of using exception handling for usage errors, you can use the Debug.Assert method to identify usage errors in debug builds, and the Trace.Assert 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. 例如, 如果用户需要以特定格式输入日期, 则可以通过调用DateTime.TryParseExact方法来分析日期字符串, 该方法返回一个Boolean指示分析操作是否成功的值, 而不是使用DateTime.ParseExact方法, 如果无法将FormatException日期字符串DateTime转换为值, 则会引发异常。For example, if the user is expected to input a date in a particular format, you can parse the date string by calling the DateTime.TryParseExact method, which returns a Boolean value that indicates whether the parse operation succeeded, instead of using the DateTime.ParseExact method, which throws a FormatException exception if the date string cannot be converted to a DateTime value. 同样, 如果用户尝试打开不存在的文件, 则可以先调用File.Exists方法以检查该文件是否存在, 如果不存在, 则提示用户是否要创建该文件。Similarly, if a user tries to open a file that does not exist, you can first call the File.Exists 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. 在这种情况下, 尝试通过实例化StreamReader对象或Open调用方法打开文件可能会引发FileNotFoundException异常。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. 例如, 如果公共语言运行时无法OutOfMemoryException分配更多内存, 则任何方法都可能引发异常。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. 相反, 你可以使用事件 ( AppDomain.UnhandledException例如), 并Environment.FailFast调用方法来记录异常信息, 并在应用程序终止之前通知用户失败。Instead, you may be able to use an event such as AppDomain.UnhandledException and call the Environment.FailFast method to log exception information and notify the user of the failure before the application terminates.

Try/catch 块Try/catch blocks

公共语言运行时提供异常处理模型, 该模型基于作为对象的异常表示形式, 并将程序代码和异常处理代码try与块和catch块分离。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. 可以有一个或多个catch块, 每个块用于处理特定类型的异常, 或一个块旨在捕获比另一个块更具体的异常。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.

如果应用程序处理在执行应用程序代码块的过程中发生的异常, 则必须将代码放置在try语句中并将其try称为块。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. 处理try块引发的异常的应用程序代码放置在一个catch catch语句中, 称为块。Application code that handles exceptions thrown by a try block is placed within a catch statement and is called a catch block. 与块关联catch的零个或多个块, 每catch个块都包含一个类型筛选器, 用于确定它处理的异常的类型。 tryZero 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.

如果try块中发生异常, 则系统将按照它们在应用catch程序代码中出现的顺序搜索关联的块catch , 直到它找到处理异常的块。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. 如果 catch 块的类型筛选器指定T或从派生的任何类型, T则块将处理类型T为的异常。 catchA 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. 系统在找到处理异常的第一个catch块后停止搜索。The system stops searching after it finds the first catch block that handles the exception. 出于此原因, 在应用程序代码中catch , 处理类型的块必须在处理其基catch类型的块之前指定, 如本部分后面的示例中所示。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. 最后指定处理System.Exception程序的 catch 块。A catch block that handles System.Exception is specified last.

如果与当前trycatch关联的所有块均未处理异常, 并且当前try块嵌套在当前调用的其他try块中, 则catch为与下一个关联的块搜索try封闭块。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. 如果未catch找到异常的块, 则系统会在当前调用中搜索先前的嵌套级别。If no catch block for the exception is found, the system searches previous nesting levels in the current call. 如果在catch当前调用中找不到异常的块, 则将在调用堆栈中向上传递异常, 并在上一堆栈帧中搜索catch处理异常的块。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. 如果到达调用堆栈顶部但未找到catch处理异常的块, 则默认异常处理程序将处理该异常, 并且应用程序将终止。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. 此短信保存在异常对象Message的属性中。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. 有关更多信息,请参见 Message 属性。For more information, see the Message property.

  • 引发异常时的调用堆栈的状态。The state of the call stack when the exception was thrown. StackTrace属性带有一个可用于确定代码中错误发生位置的堆栈跟踪。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

Message Source HResult StackTrace HelpLink InnerException类包含多个属性, 这些属性可帮助标识代码位置、类型、帮助文件和异常的原因:、、、、、、 ExceptionTargetSite、和DataThe 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.

当两个或多个异常之间存在因果关系时InnerException , 属性将保留该信息。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. 有关异常的补充信息可以存储为Data属性中的键/值对的集合。Supplementary information about the exception can be stored as a collection of key/value pairs in the Data property.

在创建异常对象的过程中, 传递给构造函数的错误消息字符串应本地化, 并可通过使用ResourceManager类从资源文件提供。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 and Packaging and Deploying Resources topics.

若要为用户提供有关异常发生原因的详细信息, HelpLink属性可以将 URL (或 URN) 保存到帮助文件。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.

Exception类使用的 HRESULT COR_E_EXCEPTION, 其值为0x80131500。The Exception class uses the HRESULT COR_E_EXCEPTION, which has the value 0x80131500.

有关Exception类的实例的初始属性值的列表, Exception请参见构造函数。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.

重新引发异常Re-throwing an exception

在许多情况下, 异常处理程序只需要将异常传递给调用方。In many cases, an exception handler simply wants to pass the exception on to the caller. 最常见的情况是:This most often occurs in:

  • 一个类库, 用于包装对 .NET Framework 类库或其他类库中的方法的调用。A class library that in turn wraps calls to methods in the .NET Framework class library or other class libraries.

  • 遇到严重异常的应用程序或库。An application or library that encounters a fatal exception. 异常处理程序可以记录异常, 然后重新引发异常。The exception handler can log the exception and then re-throw the exception.

重新引发异常的建议方法是只使用中C#的throw语句和 Visual Basic 中的throw语句, 而不包括表达式。The recommended way to re-throw an exception is to simply use the throw statement in C# and the Throw statement in Visual Basic without including an expression. 这可确保在异常传播到调用方时, 保留所有调用堆栈信息。This ensures that all call stack information is preserved when the exception is propagated to the caller. 下面的示例阐释了这一点。The following example illustrates this. 字符串扩展方法FindOccurrences将一个或多个调用包装到String.IndexOf(String, Int32) , 但不事先验证其参数。A string extension method, FindOccurrences, wraps one or more calls to String.IndexOf(String, Int32) without validating its arguments beforehand.

using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

public static class Library
{
   public static int[] FindOccurrences(this String s, String f)
   {
      var indexes = new List<int>();
      int currentIndex = 0;
      try {
         while (currentIndex >= 0 && currentIndex < s.Length) {
            currentIndex = s.IndexOf(f, currentIndex);
            if (currentIndex >= 0) {
               indexes.Add(currentIndex);
               currentIndex++;
            }
         }
      }
      catch (ArgumentNullException e) {
         // Perform some action here, such as logging this exception.

         throw;
      }
      return indexes.ToArray();
   }
}
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices

Public Module Library
   <Extension()>
   Public Function FindOccurrences(s As String, f As String) As Integer()
      Dim indexes As New List(Of Integer)
      Dim currentIndex As Integer = 0
      Try
         Do While currentIndex >= 0 And currentIndex < s.Length
            currentIndex = s.IndexOf(f, currentIndex)
            If currentIndex >= 0 Then
               indexes.Add(currentIndex)
               currentIndex += 1
            End If
         Loop
      Catch e As ArgumentNullException
         ' Perform some action here, such as logging this exception.
         
         Throw
      End Try
      Return indexes.ToArray()
   End Function
End Module

然后, 调用方FindOccurrences调用两次。A caller then calls FindOccurrences twice. 在第二次调用FindOccurrences中, 调用方将null作为搜索String.IndexOf(String, Int32)字符串进行传递, 这将引发ArgumentNullException异常。In the second call to FindOccurrences, the caller passes a null as the search string, which cases the String.IndexOf(String, Int32) method to throw an ArgumentNullException exception. 此异常由FindOccurrences方法进行处理并传递回调用方。This exception is handled by the FindOccurrences method and passed back to the caller. 由于 throw 语句与 no 表达式一起使用, 因此该示例的输出显示调用堆栈被保留。Because the throw statement is used with no expression, the output from the example shows that the call stack is preserved.

public class Example
{
   public static void Main()
   {
      String s = "It was a cold day when...";
      int[] indexes = s.FindOccurrences("a");
      ShowOccurrences(s, "a", indexes);
      Console.WriteLine();
      
      String toFind = null;
      try {
         indexes = s.FindOccurrences(toFind);
         ShowOccurrences(s, toFind, indexes);
      }
      catch (ArgumentNullException e) {
         Console.WriteLine("An exception ({0}) occurred.",
                           e.GetType().Name);
         Console.WriteLine("Message:\n   {0}\n", e.Message);
         Console.WriteLine("Stack Trace:\n   {0}\n", e.StackTrace);
      }
   }

   private static void ShowOccurrences(String s, String toFind, int[] indexes)
   {
      Console.Write("'{0}' occurs at the following character positions: ",
                    toFind);
      for (int ctr = 0; ctr < indexes.Length; ctr++)
         Console.Write("{0}{1}", indexes[ctr],
                       ctr == indexes.Length - 1 ? "" : ", ");

      Console.WriteLine();
   }
}
// The example displays the following output:
//    'a' occurs at the following character positions: 4, 7, 15
//
//    An exception (ArgumentNullException) occurred.
//    Message:
//       Value cannot be null.
//    Parameter name: value
//
//    Stack Trace:
//          at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
//    ngComparison comparisonType)
//       at Library.FindOccurrences(String s, String f)
//       at Example.Main()
Module Example
   Public Sub Main()
      Dim s As String = "It was a cold day when..."
      Dim indexes() As Integer = s.FindOccurrences("a")
      ShowOccurrences(s, "a", indexes)
      Console.WriteLine()

      Dim toFind As String = Nothing
      Try
         indexes = s.FindOccurrences(toFind)
         ShowOccurrences(s, toFind, indexes)
      Catch e As ArgumentNullException
         Console.WriteLine("An exception ({0}) occurred.",
                           e.GetType().Name)
         Console.WriteLine("Message:{0}   {1}{0}", vbCrLf, e.Message)
         Console.WriteLine("Stack Trace:{0}   {1}{0}", vbCrLf, e.StackTrace)
      End Try
   End Sub
   
   Private Sub ShowOccurrences(s As String, toFind As String, indexes As Integer())
      Console.Write("'{0}' occurs at the following character positions: ",
                    toFind)
      For ctr As Integer = 0 To indexes.Length - 1
         Console.Write("{0}{1}", indexes(ctr),
                       If(ctr = indexes.Length - 1, "", ", "))
      Next
      Console.WriteLine()
   End Sub
End Module
' The example displays the following output:
'    'a' occurs at the following character positions: 4, 7, 15
'
'    An exception (ArgumentNullException) occurred.
'    Message:
'       Value cannot be null.
'    Parameter name: value
'
'    Stack Trace:
'          at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
'    ngComparison comparisonType)
'       at Library.FindOccurrences(String s, String f)
'       at Example.Main()

相反, 如果使用引发异常,In contrast, if the exception is re-thrown by using the

throw e;
Throw e  

语句时, 将不保留完全调用堆栈, 示例将生成以下输出:statement, the full call stack is not preserved, and the example would generate the following output:


'a' occurs at the following character positions: 4, 7, 15  

An exception (ArgumentNullException) occurred.  
Message:  
   Value cannot be null.  
Parameter name: value  

Stack Trace:  
      at Library.FindOccurrences(String s, String f)  
   at Example.Main()  

一种更繁琐的替代方法是引发新异常, 并在内部异常中保留原始异常的调用堆栈信息。A slightly more cumbersome alternative is to throw a new exception, and to preserve the original exception's call stack information in an inner exception. 然后, 调用方可以使用新异常的InnerException属性来检索堆栈帧以及有关原始异常的其他信息。The caller can then use the new exception's InnerException property to retrieve stack frame and other information about the original exception. 在这种情况下, throw 语句为:In this case, the throw statement is:

throw new ArgumentNullException("You must supply a search string.",
                                e);
Throw New ArgumentNullException("You must supply a search string.",
                                e)

处理异常的用户代码必须知道InnerException属性包含有关原始异常的信息, 如下面的异常处理程序所示。The user code that handles the exception has to know that the InnerException property contains information about the original exception, as the following exception handler illustrates.

try {
   indexes = s.FindOccurrences(toFind);
   ShowOccurrences(s, toFind, indexes);
}
catch (ArgumentNullException e) {
   Console.WriteLine("An exception ({0}) occurred.",
                     e.GetType().Name);
   Console.WriteLine("   Message:\n{0}", e.Message);
   Console.WriteLine("   Stack Trace:\n   {0}", e.StackTrace);
   Exception ie = e.InnerException;
   if (ie != null) {
      Console.WriteLine("   The Inner Exception:");
      Console.WriteLine("      Exception Name: {0}", ie.GetType().Name);
      Console.WriteLine("      Message: {0}\n", ie.Message);
      Console.WriteLine("      Stack Trace:\n   {0}\n", ie.StackTrace);
   }
}
// The example displays the following output:
//    'a' occurs at the following character positions: 4, 7, 15
//
//    An exception (ArgumentNullException) occurred.
//       Message: You must supply a search string.
//
//       Stack Trace:
//          at Library.FindOccurrences(String s, String f)
//       at Example.Main()
//
//       The Inner Exception:
//          Exception Name: ArgumentNullException
//          Message: Value cannot be null.
//    Parameter name: value
//
//          Stack Trace:
//          at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
//    ngComparison comparisonType)
//       at Library.FindOccurrences(String s, String f)
Try
   indexes = s.FindOccurrences(toFind)
   ShowOccurrences(s, toFind, indexes)
Catch e As ArgumentNullException
   Console.WriteLine("An exception ({0}) occurred.",
                     e.GetType().Name)
   Console.WriteLine("   Message: {1}{0}", vbCrLf, e.Message)
   Console.WriteLine("   Stack Trace:{0}   {1}{0}", vbCrLf, e.StackTrace)
   Dim ie As Exception = e.InnerException
   If ie IsNot Nothing Then
      Console.WriteLine("   The Inner Exception:")
      Console.WriteLine("      Exception Name: {0}", ie.GetType().Name)
      Console.WriteLine("      Message: {1}{0}", vbCrLf, ie.Message)
      Console.WriteLine("      Stack Trace:{0}   {1}{0}", vbCrLf, ie.StackTrace)
   End If
End Try
' The example displays the following output:
'       'a' occurs at the following character positions: 4, 7, 15
'
'       An exception (ArgumentNullException) occurred.
'          Message: You must supply a search string.
'
'          Stack Trace:
'             at Library.FindOccurrences(String s, String f)
'          at Example.Main()
'
'          The Inner Exception:
'             Exception Name: ArgumentNullException
'             Message: Value cannot be null.
'       Parameter name: value
'
'             Stack Trace:
'             at System.String.IndexOf(String value, Int32 startIndex, Int32 count, Stri
'       ngComparison comparisonType)
'          at Library.FindOccurrences(String s, String f)

选择标准异常Choosing standard exceptions

当必须引发异常时, 通常可以使用 .NET Framework 中的现有异常类型, 而不是实现自定义异常。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). 通常情况下ArgumentException, 会引发异常, 如、 ArgumentNullExceptionInvalidOperationException或。 NotSupportedExceptionTypically, 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. 有关更多信息,请参见 Message 属性。For more information, see the Message property.

  • 你正在处理一个错误, 该错误可以通过现有 .NET Framework 异常传达给调用方。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. 例如, 如果某个方法要求参数为枚举类型的有效成员, 则应引发InvalidEnumArgumentException (派生程度最高的类) 而不是。 ArgumentExceptionFor 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 传递给方法的非 null 参数无效。A non-null argument that is passed to a method is invalid.
ArgumentNullException 传递给方法的参数是nullAn argument that is passed to a method is null.
ArgumentOutOfRangeException 参数超出了有效值的范围。An argument is outside the range of valid values.
DirectoryNotFoundException 部分目录路径无效。Part of a directory path is not valid.
DivideByZeroException 整数或Decimal除法运算中的分母为零。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 值的格式不正确, 无法通过转换方法 (如) Parse从字符串进行转换。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 使用了无效的统一资源标识符 (URI)。An invalid Uniform Resource Identifier (URI) is used.

实现自定义异常Implementing custom exceptions

在以下情况下, 使用现有 .NET Framework 异常来处理错误条件是不够的:In the following cases, using an existing .NET Framework exception to handle an error condition is not adequate:

  • 如果异常反映了无法映射到现有 .NET Framework 异常的唯一程序错误, 则为。When the exception reflects a unique program error that cannot be mapped to an existing .NET Framework exception.

  • 当异常要求的处理与适用于现有 .NET Framework 异常的处理不同时, 或者必须从类似的异常中消除异常时。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. 例如, 如果在分析超出目标ArgumentOutOfRangeException整数类型范围的字符串的数值表示形式时引发异常, 则不希望对由调用方提供的错误产生的错误使用相同的异常调用方法时相应的约束值。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.

Exception类是 .NET Framework 中所有异常的基类。The Exception class is the base class of all exceptions in the .NET Framework. 许多派生类依赖于Exception类的成员的继承行为; 它们不会重写的Exception成员, 也不定义任何唯一成员。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. 定义继承自Exception的类。Define a class that inherits from Exception. 如有必要, 定义类所需的任何唯一成员以提供有关异常的其他信息。If necessary, define any unique members needed by your class to provide additional information about the exception. 例如, ArgumentException类包含一个ParamName属性, 该属性指定其自变量导致异常的参数的名称, 而RegexMatchTimeoutException属性包含一个MatchTimeout指示超时间隔的属性。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. 请注意, 的Exception大多数现有派生类不会重写继承成员的行为。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. 若要使异常对象可序列化, 请用SerializableAttribute特性标记它。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:

下面的示例演示如何使用自定义异常类。The following example illustrates the use of a custom exception class. 它定义一个NotPrimeException异常, 当客户端尝试通过指定不是质数的起始数字来检索质数序列时, 将引发此异常。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. 异常定义了一个新的属性NonPrime, 该属性返回导致异常的非质数。The exception defines a new property, NonPrime, that returns the non-prime number that caused the exception. 除了使用SerializationInfo和序列化和StreamingContext NotPrimeException参数实现受保护的无参数构造函数和构造函数以外, NonPrime类还定义了三个其他构造函数来支持属性。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. NotPrimeException类还SerializableAttribute用特性标记。The NotPrimeException class is also marked with the SerializableAttribute attribute.

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; } }
}
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

下面的示例中所示的类使用尼斯筛法的埃拉托色,计算从2到客户端在调用其类构造函数时指定的限制的质数序列。PrimeNumberGeneratorThe 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. 方法返回大于或等于指定下限的所有质数, 但NotPrimeException如果下限不是质数, 则会引发。 GetPrimesFromThe 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.

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

下面的示例对具有非质数的GetPrimesFrom方法进行两次调用, 其中一个值与应用程序域边界交叉。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.

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("--------");
      }
   }
}
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()
'      --------

Windows 运行时和.NET Framework 4.5.1.NET Framework 4.5.1Windows Runtime and .NET Framework 4.5.1.NET Framework 4.5.1

适用于 Windows 8.x 应用商店应用的 .NET.NET for Windows 8.x Store apps 对于Windows 8Windows 8, 在通过 non-.NET Framework 堆栈帧传播异常时, 某些异常信息通常会丢失。In 适用于 Windows 8.x 应用商店应用的 .NET.NET for Windows 8.x Store apps for Windows 8Windows 8, some exception information is typically lost when an exception is propagated through non-.NET Framework stack frames. .NET Framework 4.5.1.NET Framework 4.5.1从和Windows 8.1Windows 8.1开始, 公共语言运行时将继续使用引发的原始Exception对象, 除非在 non-.NET Framework 堆栈帧中修改了该异常。Starting with the .NET Framework 4.5.1.NET Framework 4.5.1 and Windows 8.1Windows 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.

构造函数

Exception() Exception() Exception() Exception()

初始化 Exception 类的新实例。Initializes a new instance of the Exception class.

Exception(SerializationInfo, StreamingContext) Exception(SerializationInfo, StreamingContext) Exception(SerializationInfo, StreamingContext) Exception(SerializationInfo, StreamingContext)

用序列化数据初始化 Exception 类的新实例。Initializes a new instance of the Exception class with serialized data.

Exception(String) Exception(String) Exception(String) Exception(String)

用指定的错误消息初始化 Exception 类的新实例。Initializes a new instance of the Exception class with a specified error message.

Exception(String, Exception) Exception(String, Exception) Exception(String, Exception) Exception(String, Exception)

使用指定的错误消息和对作为此异常原因的内部异常的引用来初始化 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.

属性

Data Data Data Data

获取提供有关异常的其他用户定义信息的键/值对集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

HelpLink HelpLink HelpLink HelpLink

获取或设置指向与此异常关联的帮助文件链接。Gets or sets a link to the help file associated with this exception.

HResult HResult HResult HResult

获取或设置 HRESULT(一个分配给特定异常的编码数字值)。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

InnerException InnerException InnerException InnerException

获取导致当前异常的 Exception 实例。Gets the Exception instance that caused the current exception.

Message Message Message Message

获取描述当前异常的消息。Gets a message that describes the current exception.

Source Source Source Source

获取或设置导致错误的应用程序或对象的名称。Gets or sets the name of the application or the object that causes the error.

StackTrace StackTrace StackTrace StackTrace

获取调用堆栈上的即时框架字符串表示形式。Gets a string representation of the immediate frames on the call stack.

TargetSite TargetSite TargetSite TargetSite

获取引发当前异常的方法。Gets the method that throws the current exception.

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBaseException() GetBaseException() GetBaseException() GetBaseException()

当在派生类中重写时,返回 Exception,它是一个或多个并发的异常的根源。When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

当在派生类中重写时,用关于异常的信息设置 SerializationInfoWhen overridden in a derived class, sets the SerializationInfo with information about the exception.

GetType() GetType() GetType() GetType()

获取当前实例的运行时类型。Gets the runtime type of the current instance.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

创建并返回当前异常的字符串表示形式。Creates and returns a string representation of the current exception.

事件

SerializeObjectState SerializeObjectState SerializeObjectState SerializeObjectState

当异常被序列化用来创建包含有关该异常的徐列出数据的异常状态对象时会出现该问题。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

适用于

另请参阅