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)]
[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. 如需詳細資訊,請參閱 < Managed 程式碼中的判斷提示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例外狀況,如果 common language runtime 無法配置額外的記憶體。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

Common language runtime 提供的例外狀況處理模型為基礎的例外狀況物件,表示和的程式碼和例外狀況處理程式碼分隔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. Acatch區塊處理例外狀況型別的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 屬性 (Property)。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 屬性 (Property)。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. 序列化可讓您儲存例外狀況的相關資訊,並允許遠端執行功能的內容中共用的一部伺服器和用戶端 proxy 的例外狀況資訊。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:

    • Exception()會使用預設值來初始化新的例外狀況物件的屬性。Exception(), which uses default values to initialize the properties of a new exception object.

    • Exception(String)其中,初始化新的例外狀況物件,使用指定的錯誤訊息。Exception(String), which initializes a new exception object with a specified error message.

    • Exception(String, Exception)其中,初始化新的例外狀況物件,使用指定的錯誤訊息和內部例外狀況。Exception(String, Exception), which initializes a new exception object with a specified error message and inner exception.

    • Exception(SerializationInfo, StreamingContext)這是protected建構函式,初始化新的例外狀況物件,從序列化資料。Exception(SerializationInfo, StreamingContext), which is a protected constructor that initializes a new exception object from serialized data. 如果您選擇要讓例外狀況物件的可序列化,您應該實作這個建構函式。You should implement this constructor if you've chosen to make your exception object serializable.

下列範例說明如何使用自訂例外狀況類別。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下列範例所示的類別會使用 Sieve Eratosthenes 計算質數 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 apps針對Windows 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)

在衍生類別中覆寫時,使用例外狀況的資訊設定 SerializationInfo When 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 的淺層複本 (Shallow Copy)。 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.

適用於

另請參閱