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: {0}", e.ToString());
         }
         catch (Exception e) 
         {
            Console.WriteLine("Generic Exception Handler: {0}", e.ToString());
         }
   }	
}
/*
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
    

    NullReferenceException产生的异常时objnull可通过修改源代码,以显式测试是否为 null 之前,调用来消除Object.Equals重写和重新编译。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. 程序错误是一定不能通过编写无 bug 的代码来避免运行时错误。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块下与相关联try块中,并且每个catch块包含类型筛选器,用于确定它处理的异常的类型。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.

在异常发生时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如果 catch 块的类型筛选器指定T或任何类型的T派生。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. 系统会停止搜索后查找第一个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. 处理的 catch 块System.Exception最后指定。A catch block that handles System.Exception is specified last.

如果没有catch与当前相关联的块try块处理异常,并且当前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

Exception类还包含一些属性,可帮助识别代码位置、 类型、 帮助文件和异常的原因: StackTraceInnerExceptionMessageHelpLinkHResultSourceTargetSite,和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.

此外,不会引发异常时返回代码是不够的;没有转换为异常,则返回代码并不定期执行 catch 异常、 忽略它,并再继续进行处理。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# 中的语句和引发在 Visual Basic 中不包含表达式的语句。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 语句使用不包含表达式,该示例输出所示保留调用堆栈。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). 通常情况下,会如引发异常ArgumentExceptionArgumentNullExceptionInvalidOperationException,或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 值不在相应的格式将待换算从字符串转换方法如ParseA 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. 定义一个类,继承自ExceptionDefine 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. 除了实现受保护的无参数构造函数和一个构造函数与SerializationInfoStreamingContext序列化的参数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

PrimeNumberGenerator类在下面的示例所示使用埃拉托色的埃拉托色尼斯来计算的一系列质数从 2 到客户端对其类构造函数的调用中指定的限制。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. GetPrimesFrom方法返回大于或等于指定的下限值的所有质数,但会引发NotPrimeException如果该较低的限制不是一个素数。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.

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 appsWindows 8Windows 8,通过.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.1Windows 8.1Windows 8.1,公共语言运行时仍会继续使用原始Exception除非已在.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.

适用于

另请参阅