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 也會catch攔截ArithmeticException錯誤,因為衍生自,而且沒有明確定義錯誤的DivideByZeroException區塊。 DivideByZeroExceptionThis catch block also catches DivideByZeroException errors, because DivideByZeroException derives from ArithmeticException and there is no catch block explicitly defined for DivideByZeroException errors.

using namespace System;
int main()
{
    int x = 0;
    try
    {
        int y = 100 / x;
    }
    catch ( ArithmeticException^ e ) 
    {
        Console::WriteLine( "ArithmeticException Handler: {0}", e );
    }
    catch ( Exception^ e ) 
    {
        Console::WriteLine( "Generic Exception Handler: {0}", e );
    }
}
/*
This code example produces the following results:

ArithmeticException Handler: System.DivideByZeroException: Attempted to divide by zero.
   at main()
 
*/
using System;

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

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

*/
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
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呼叫覆Object.Equals寫然後obj重新null編譯之前,可以藉由修改原始程式碼以明確測試 null,來消除所產生的例外狀況。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方法來識別 debug 組建中的使用錯誤,以及識別在 debug 和 release 組建中使用錯誤的Trace.Assert方法。Instead of using exception handling for usage errors, you can use the Debug.Assert method to identify usage errors in debug builds, and the Trace.Assert method to identify usage errors in both debug and release builds. 如需詳細資訊,請參閱受控碼中的判斷提示For more information, see Assertions in Managed Code.

  • 程式錯誤。Program errors. 程式錯誤是執行階段錯誤,不一定要藉由撰寫無錯誤的程式碼來避免。A program error is a run-time error that cannot necessarily be avoided by writing bug-free code.

    在某些情況下,程式錯誤可能會反映預期或例行的錯誤狀況。In some cases, a program error may reflect an expected or routine error condition. 在此情況下,您可能會想要避免使用例外狀況處理來處理常式錯誤,並改為重試作業。In this case, you may want to avoid using exception handling to deal with the program error and instead retry the operation. 例如,如果使用者預期會以特定格式輸入日期,您可以藉由呼叫DateTime.TryParseExact方法來剖析日期字串,這Boolean會傳回表示剖析作業是否成功的值,而不是使用DateTime.ParseExact方法,如果日期字串FormatException無法DateTime轉換為值,則會擲回例外狀況。For example, if the user is expected to input a date in a particular format, you can parse the date string by calling the DateTime.TryParseExact method, which returns a Boolean value that indicates whether the parse operation succeeded, instead of using the DateTime.ParseExact method, which throws a FormatException exception if the date string cannot be converted to a DateTime value. 同樣地,如果使用者嘗試開啟不存在的檔案,您可以先呼叫File.Exists方法來檢查檔案是否存在,如果沒有,則會提示使用者是否要建立檔案。Similarly, if a user tries to open a file that does not exist, you can first call the File.Exists method to check whether the file exists and, if it does not, prompt the user whether he or she wants to create it.

    在其他情況下,程式錯誤會反映出可在您程式碼中處理的非預期錯誤狀況。In other cases, a program error reflects an unexpected error condition that can be handled in your code. 例如,即使您已檢查以確定檔案存在,在開啟檔案或可能已損毀之前,可能會先將它刪除。For example, even if you've checked to ensure that a file exists, it may be deleted before you can open it, or it may be corrupted. 在此情況下,嘗試藉由具現化StreamReader物件或Open呼叫方法來開啟檔案,可能FileNotFoundException會擲回例外狀況。In that case, trying to open the file by instantiating a StreamReader object or calling the Open method may throw a FileNotFoundException exception. 在這些情況下,您應該使用例外狀況處理來從錯誤中復原。In these cases, you should use exception handling to recover from the error.

  • 系統失敗。System failures. 系統失敗是執行階段錯誤,無法以有意義的方式處理。A system failure is a run-time error that cannot be handled programmatically in a meaningful way. 例如,如果 common language runtime 無法配置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 T或衍生自的任何類型, T區塊會處理類型的例外狀況。 catchA catch block handles an exception of type T if the type filter of the catch block specifies T or any type that T derives from. 系統會在找到處理例外狀況的第catch一個區塊之後,停止搜尋。The system stops searching after it finds the first catch block that handles the exception. 因此,在應用程式代碼中, catch處理類型的區塊必須在處理其基底類型的catch區塊之前指定,如本節中的範例所示。For this reason, in application code, a catch block that handles a type must be specified before a catch block that handles its base types, as demonstrated in the example that follows this section. 最後指定處理System.Exception的 catch 區塊。A catch block that handles System.Exception is specified last.

如果與目前try區塊catch相關聯的區塊都不會處理例外狀況,而且目前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

Message Source HResult StackTrace HelpLink InnerException類別包含數個屬性,可協助識別程式碼位置、類型、說明檔,以及例外狀況的原因:、、、、、、 ExceptionTargetSite、和DataThe Exception class includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: StackTrace, InnerException, Message, HelpLink, HResult, Source, TargetSite, and Data.

當兩個或多個例外狀況之間存在因果關係InnerException時,屬性會保留這項資訊。When a causal relationship exists between two or more exceptions, the InnerException property maintains this information. 回應這個內部例外狀況時,會擲回外部例外狀況。The outer exception is thrown in response to this inner exception. 處理外部例外狀況的程式碼可以使用舊版內部例外狀況的資訊,更適當地處理錯誤。The code that handles the outer exception can use the information from the earlier inner exception to handle the error more appropriately. 有關例外狀況的補充資訊可以儲存為Data屬性中的索引鍵/值組集合。Supplementary information about the exception can be stored as a collection of key/value pairs in the Data property.

在建立例外狀況物件期間傳遞給此函式的錯誤訊息字串,應該會進行當地語系化,並可使用ResourceManager類別從資源檔提供。The error message string that is passed to the constructor during the creation of the exception object should be localized and can be supplied from a resource file by using the ResourceManager class. 如需當地語系化資源的詳細資訊,請參閱建立附屬元件封裝和部署資源主題。For more information about localized resources, see the Creating Satellite Assemblies and Packaging and Deploying Resources topics.

若要為使用者提供例外狀況發生原因的詳細資訊, HelpLink屬性可以將 URL (或 URN)存放至說明檔。To provide the user with extensive information about why the exception occurred, the HelpLink property can hold a URL (or URN) to a help file.

Exception類別會使用 HRESULT COR_E_EXCEPTION,其值為0x80131500。The Exception class uses the HRESULT COR_E_EXCEPTION, which has the value 0x80131500.

如需Exception類別實例的初始屬性值清單, Exception請參閱函式。For a list of initial property values for an instance of the Exception class, see the Exception constructors.

效能考量Performance considerations

擲回或處理例外狀況會耗用大量的系統資源和執行時間。Throwing or handling an exception consumes a significant amount of system resources and execution time. 只會擲回例外狀況,以處理真正的特殊條件,而不是處理可預測的事件或流量控制。Throw exceptions only to handle truly extraordinary conditions, not to handle predictable events or flow control. 例如,在某些情況下(例如當您開發類別庫時),如果方法引數無效,就一定會擲回例外狀況,因為您預期會使用有效的參數來呼叫方法。For example, in some cases, such as when you're developing a class library, it's reasonable to throw an exception if a method argument is invalid, because you expect your method to be called with valid parameters. 不正確方法引數(如果不是使用錯誤的結果),表示發生了一項特別的問題。An invalid method argument, if it is not the result of a usage error, means that something extraordinary has occurred. 相反地,如果使用者輸入無效,也不會擲回例外狀況,因為您可以預期使用者偶爾會輸入不正確資料。Conversely, do not throw an exception if user input is invalid, because you can expect users to occasionally enter invalid data. 相反地,請提供重試機制,讓使用者可以輸入有效的輸入。Instead, provide a retry mechanism so users can enter valid input. 您也不應該使用例外狀況來處理使用錯誤。Nor should you use exceptions to handle usage errors. 相反地,請使用判斷提示來識別和更正使用錯誤。Instead, use assertions to identify and correct usage errors.

此外,當傳回碼足夠時,不會擲回例外狀況;不要將傳回碼轉換成例外狀況;和不會定期攔截例外狀況、忽略它,然後繼續處理。In addition, do not throw an exception when a return code is sufficient; do not convert a return code to an exception; and do not routinely catch an exception, ignore it, and then continue processing.

重新擲回例外狀況Re-throwing an exception

在許多情況下,例外狀況處理常式只會想要將例外狀況傳遞給呼叫者。In many cases, an exception handler simply wants to pass the exception on to the caller. 最常見的情況如下:This most often occurs in:

  • 類別庫,接著會將呼叫包裝 .NET Framework Class Library 或其他類別庫中的方法。A class library that in turn wraps calls to methods in the .NET Framework class library or other class libraries.

  • 遇到嚴重例外狀況的應用程式或程式庫。An application or library that encounters a fatal exception. 例外狀況處理常式可以記錄例外狀況,然後重新擲回例外狀況。The exception handler can log the exception and then re-throw the exception.

若要重新擲回例外狀況,建議的方法是只使用中C#的 throw 語句和 Visual Basic 中的throw語句,而不包含運算式。The recommended way to re-throw an exception is to simply use the throw statement in C# and the Throw statement in Visual Basic without including an expression. 這可確保在將例外狀況傳播至呼叫端時,會保留所有的呼叫堆疊資訊。This ensures that all call stack information is preserved when the exception is propagated to the caller. 下列範例將說明這點。The following example illustrates this. 字串擴充方法FindOccurrences會包裝一或多個對String.IndexOf(String, Int32)的呼叫,而不事先驗證其引數。A string extension method, FindOccurrences, wraps one or more calls to String.IndexOf(String, Int32) without validating its arguments beforehand.

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

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

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

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

呼叫者接著呼叫FindOccurrences兩次。A caller then calls FindOccurrences twice. 在第二次呼叫FindOccurrences null時,呼叫端會傳遞做為搜尋字串,這種String.IndexOf(String, Int32)情況下會擲ArgumentNullException回例外狀況的方法。In the second call to FindOccurrences, the caller passes a null as the search string, which cases the String.IndexOf(String, Int32) method to throw an ArgumentNullException exception. 這個例外狀況是由FindOccurrences方法處理,並傳回給呼叫者。This exception is handled by the FindOccurrences method and passed back to the caller. 由於 throw 語句會用於沒有運算式,因此此範例的輸出會顯示已保留呼叫堆疊。Because the throw statement is used with no expression, the output from the example shows that the call stack is preserved.

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

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

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

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

相反地,如果使用來重新擲回例外狀況,In contrast, if the exception is re-thrown by using the

throw e;
Throw e  

語句,不會保留完整的呼叫堆疊,此範例會產生下列輸出:statement, the full call stack is not preserved, and the example would generate the following output:


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

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

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

稍微棘手的替代方法是擲回新的例外狀況,並將原始例外狀況的呼叫堆疊資訊保留在內部例外狀況中。A slightly more cumbersome alternative is to throw a new exception, and to preserve the original exception's call stack information in an inner exception. 呼叫者接著可以使用新的例外狀況InnerException的屬性來抓取堆疊框架,以及有關原始例外狀況的其他資訊。The caller can then use the new exception's InnerException property to retrieve stack frame and other information about the original exception. 在此情況下,throw 語句為:In this case, the throw statement is:

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

處理例外狀況的使用者程式碼必須知道InnerException屬性包含原始例外狀況的相關資訊,如下列例外狀況處理常式所示。The user code that handles the exception has to know that the InnerException property contains information about the original exception, as the following exception handler illustrates.

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

選擇標準例外狀況Choosing standard exceptions

當您必須擲回例外狀況時,您通常可以在 .NET Framework 中使用現有的例外狀況類型,而不是執行自訂例外狀況。When you have to throw an exception, you can often use an existing exception type in the .NET Framework instead of implementing a custom exception. 在這兩種情況下,您應該使用標準的例外狀況類型:You should use a standard exception type under these two conditions:

  • 您擲回的例外狀況是由使用錯誤所造成(也就是,由呼叫您方法的開發人員所提出的程式邏輯錯誤)。You are throwing an exception that is caused by a usage error (that is, by an error in program logic made by the developer who is calling your method). 一般來說,您會擲回例外狀況, ArgumentException例如ArgumentNullExceptionInvalidOperationException、或NotSupportedExceptionTypically, you would throw an exception such as ArgumentException, ArgumentNullException, InvalidOperationException, or NotSupportedException. 當具現化例外狀況物件時,您提供給例外狀況物件之函式的字串應該會描述錯誤,讓開發人員可以加以修正。The string you supply to the exception object's constructor when instantiating the exception object should describe the error so that the developer can fix it. 如需詳細資訊,請參閱 Message 屬性 (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回(最衍生的類別),而不ArgumentException是。For example, if a method requires an argument to be a valid member of an enumeration type, you should throw an InvalidEnumArgumentException (the most derived class) rather than an ArgumentException.

下表列出常見的例外狀況類型,以及您要擲回它們的條件。The following table lists common exception types and the conditions under which you would throw them.

例外Exception 條件Condition
ArgumentException 傳遞給方法的非 null 引數無效。A non-null argument that is passed to a method is invalid.
ArgumentNullException 傳遞至方法的引數為nullAn argument that is passed to a method is null.
ArgumentOutOfRangeException 引數超出有效值的範圍。An argument is outside the range of valid values.
DirectoryNotFoundException 目錄路徑的一部分無效。Part of a directory path is not valid.
DivideByZeroException 整數或Decimal除法運算中的分母為零。The denominator in an integer or Decimal division operation is zero.
DriveNotFoundException 磁片磁碟機無法使用或不存在。A drive is unavailable or does not exist.
FileNotFoundException 檔案不存在。A file does not exist.
FormatException 值不是使用轉換方法(例如) Parse從字串轉換的適當格式。A value is not in an appropriate format to be converted from a string by a conversion method such as Parse.
IndexOutOfRangeException 索引超出陣列或集合的範圍。An index is outside the bounds of an array or collection.
InvalidOperationException 方法呼叫在物件的目前狀態中無效。A method call is invalid in an object's current state.
KeyNotFoundException 找不到用來存取集合中成員的指定索引鍵。The specified key for accessing a member in a collection cannot be found.
NotImplementedException 未執行方法或作業。A method or operation is not implemented.
NotSupportedException 不支援方法或作業。A method or operation is not supported.
ObjectDisposedException 作業是在已處置的物件上執行。An operation is performed on an object that has been disposed.
OverflowException 算術、轉型或轉換運算會導致溢位。An arithmetic, casting, or conversion operation results in an overflow.
PathTooLongException 路徑或檔案名超過系統定義的長度上限。A path or file name exceeds the maximum system-defined length.
PlatformNotSupportedException 目前的平臺不支援此操作。The operation is not supported on the current platform.
RankException 具有錯誤維度數目的陣列會傳遞至方法。An array with the wrong number of dimensions is passed to a method.
TimeoutException 分配給作業的時間間隔已過期。The time interval allotted to an operation has expired.
UriFormatException 使用了不正確統一資源識別元(URI)。An invalid Uniform Resource Identifier (URI) is used.

執行自訂例外狀況Implementing custom exceptions

在下列情況下,使用現有的 .NET Framework 例外狀況來處理錯誤情況並不足夠:In the following cases, using an existing .NET Framework exception to handle an error condition is not adequate:

  • 當例外狀況反映出無法對應至現有 .NET Framework 例外狀況的唯一程式錯誤時。When the exception reflects a unique program error that cannot be mapped to an existing .NET Framework exception.

  • 當例外狀況所需的處理與適用于現有 .NET Framework 例外狀況的處理不同,或例外狀況必須從類似的例外狀況中區分時。When the exception requires handling that is different from the handling that is appropriate for an existing .NET Framework exception, or the exception must be disambiguated from a similar exception. 例如,如果您在剖析超出ArgumentOutOfRangeException目標整數型別範圍之字串的數值標記法時擲回例外狀況,則不會想要使用相同的例外狀況來處理因呼叫者未提供呼叫方法時的適當限制值。For example, if you throw an ArgumentOutOfRangeException exception when parsing the numeric representation of a string that is out of range of the target integral type, you would not want to use the same exception for an error that results from the caller not supplying the appropriate constrained values when calling the method.

Exception類別是 .NET Framework 中所有例外狀況的基類。The Exception class is the base class of all exceptions in the .NET Framework. 許多衍生的類別都依賴Exception類別成員的繼承行為; 它們不會覆寫的Exception成員,也不會定義任何唯一的成員。Many derived classes rely on the inherited behavior of the members of the Exception class; they do not override the members of Exception, nor do they define any unique members.

若要定義您自己的例外狀況類別:To define your own exception class:

  1. 定義繼承自Exception的類別。Define a class that inherits from Exception. 如有必要,請定義您的類別所需的任何唯一成員,以提供例外狀況的其他相關資訊。If necessary, define any unique members needed by your class to provide additional information about the exception. 例如,類別所ArgumentException ParamName包含的屬性會指定其引數造成例外狀況的參數名稱, MatchTimeout而屬性則RegexMatchTimeoutException包含指出逾時間隔的屬性。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 參數來NonPrime對序列化執行受保護的無參數函式和函式以外,類別還會定義三個額外的處理常式來支援屬性。NotPrimeExceptionBesides 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. 類別也會SerializableAttribute以屬性標記。 NotPrimeExceptionThe 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範例中所示的類別會使用 Eratosthenes 的 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. 方法會傳回大於或等於指定下限的所有質數,但NotPrimeException如果較低的限制不是質數,則會擲回。 GetPrimesFromThe GetPrimesFrom method returns all prime numbers that are greater than or equal to a specified lower limit, but throws a NotPrimeException if that lower limit is not a prime number.

using System;
using System.Collections.Generic;


[Serializable]
public class PrimeNumberGenerator
{
   private const int START = 2;
   private int maxUpperBound = 10000000;
   private int upperBound;
   private bool[] primeTable;
   private List<int> primes = new List<int>();

   public PrimeNumberGenerator(int upperBound)
   {
      if (upperBound > maxUpperBound)
      {
         string message = String.Format(
                           "{0} exceeds the maximum upper bound of {1}.",
                           upperBound, maxUpperBound);
         throw new ArgumentOutOfRangeException(message);
      }
      this.upperBound = upperBound;
      // Create array and mark 0, 1 as not prime (True).
      primeTable = new bool[upperBound + 1];
      primeTable[0] = true;
      primeTable[1] = true;

      // Use Sieve of Eratosthenes to determine prime numbers.
      for (int ctr = START; ctr <= (int)Math.Ceiling(Math.Sqrt(upperBound));
            ctr++)
      {
         if (primeTable[ctr]) continue;

         for (int multiplier = ctr; multiplier <= upperBound / ctr; multiplier++)
            if (ctr * multiplier <= upperBound) primeTable[ctr * multiplier] = true;
      }
      // Populate array with prime number information.
      int index = START;
      while (index != -1)
      {
         index = Array.FindIndex(primeTable, index, (flag) => !flag);
         if (index >= 1)
         {
            primes.Add(index);
            index++;
         }
      }
   }

   public int[] GetAllPrimes()
   {
      return primes.ToArray();
   }

   public int[] GetPrimesFrom(int prime)
   {
      int start = primes.FindIndex((value) => value == prime);
      if (start < 0)
         throw new NotPrimeException(prime, String.Format("{0} is not a prime number.", prime));
      else
         return primes.FindAll((value) => value >= prime).ToArray();
   }
}
Imports System.Collections.Generic

<Serializable()> Public Class PrimeNumberGenerator
   Private Const START As Integer = 2
   Private maxUpperBound As Integer = 10000000
   Private upperBound As Integer
   Private primeTable() As Boolean
   Private primes As New List(Of Integer)

   Public Sub New(upperBound As Integer)
      If upperBound > maxUpperBound Then
         Dim message As String = String.Format(
             "{0} exceeds the maximum upper bound of {1}.",
             upperBound, maxUpperBound)
         Throw New ArgumentOutOfRangeException(message)
      End If
      Me.upperBound = upperBound
      ' Create array and mark 0, 1 as not prime (True).
      ReDim primeTable(upperBound)
      primeTable(0) = True
      primeTable(1) = True

      ' Use Sieve of Eratosthenes to determine prime numbers.
      For ctr As Integer = START To CInt(Math.Ceiling(Math.Sqrt(upperBound)))
         If primeTable(ctr) Then Continue For

         For multiplier As Integer = ctr To CInt(upperBound \ ctr)
            If ctr * multiplier <= upperBound Then primeTable(ctr * multiplier) = True
         Next
      Next
      ' Populate array with prime number information.
      Dim index As Integer = START
      Do While index <> -1
         index = Array.FindIndex(primeTable, index, Function(flag)
                                                       Return Not flag
                                                    End Function)
         If index >= 1 Then
            primes.Add(index)
            index += 1
         End If
      Loop
   End Sub

   Public Function GetAllPrimes() As Integer()
      Return primes.ToArray()
   End Function

   Public Function GetPrimesFrom(prime As Integer) As Integer()
      Dim start As Integer = primes.FindIndex(Function(value)
                                                 Return value = prime
                                              End Function)
      If start < 0 Then
         Throw New NotPrimeException(prime, String.Format("{0} is not a prime number.", prime))
      Else
         Return primes.FindAll(Function(value)
                                  Return value >= prime
                               End Function).ToArray()
      End If
   End Function
End Class

下列範例會使用非質數來GetPrimesFrom進行兩個方法的呼叫,其中一個會跨越應用程式域界限。The following example makes two calls to the GetPrimesFrom method with non-prime numbers, one of which crosses application domain boundaries. 在這兩種情況下,都會擲回例外狀況,並在用戶端程式代碼中成功處理。In both cases, the exception is thrown and successfully handled in client code.

using System;
using System.Reflection;

class Example
{
   public static void Main()
   {
      int limit = 10000000;
      PrimeNumberGenerator primes = new PrimeNumberGenerator(limit);
      int start = 1000001;
      try
      {
         int[] values = primes.GetPrimesFrom(start);
         Console.WriteLine("There are {0} prime numbers from {1} to {2}",
                           start, limit);
      }
      catch (NotPrimeException e)
      {
         Console.WriteLine("{0} is not prime", e.NonPrime);
         Console.WriteLine(e);
         Console.WriteLine("--------");
      }

      AppDomain domain = AppDomain.CreateDomain("Domain2");
      PrimeNumberGenerator gen = (PrimeNumberGenerator)domain.CreateInstanceAndUnwrap(
                                        typeof(Example).Assembly.FullName,
                                        "PrimeNumberGenerator", true,
                                        BindingFlags.Default, null,
                                        new object[] { 1000000 }, null, null);
      try
      {
         start = 100;
         Console.WriteLine(gen.GetPrimesFrom(start));
      }
      catch (NotPrimeException e)
      {
         Console.WriteLine("{0} is not prime", e.NonPrime);
         Console.WriteLine(e);
         Console.WriteLine("--------");
      }
   }
}
Imports System.Reflection

Module Example
   Sub Main()
      Dim limit As Integer = 10000000
      Dim primes As New PrimeNumberGenerator(limit)
      Dim start As Integer = 1000001
      Try
         Dim values() As Integer = primes.GetPrimesFrom(start)
         Console.WriteLine("There are {0} prime numbers from {1} to {2}",
                           start, limit)
      Catch e As NotPrimeException
         Console.WriteLine("{0} is not prime", e.NonPrime)
         Console.WriteLine(e)
         Console.WriteLine("--------")
      End Try

      Dim domain As AppDomain = AppDomain.CreateDomain("Domain2")
      Dim gen As PrimeNumberGenerator = domain.CreateInstanceAndUnwrap(
                                        GetType(Example).Assembly.FullName,
                                        "PrimeNumberGenerator", True,
                                        BindingFlags.Default, Nothing,
                                        {1000000}, Nothing, Nothing)
      Try
         start = 100
         Console.WriteLine(gen.GetPrimesFrom(start))
      Catch e As NotPrimeException
         Console.WriteLine("{0} is not prime", e.NonPrime)
         Console.WriteLine(e)
         Console.WriteLine("--------")
      End Try
   End Sub
End Module
' The example displays the following output:
'      1000001 is not prime
'      NotPrimeException: 1000001 is not a prime number.
'         at PrimeNumberGenerator.GetPrimesFrom(Int32 prime)
'         at Example.Main()
'      --------
'      100 is not prime
'      NotPrimeException: 100 is not a prime number.
'         at PrimeNumberGenerator.GetPrimesFrom(Int32 prime)
'         at Example.Main()
'      --------

Windows 執行階段和.NET Framework 4.5.1.NET Framework 4.5.1Windows Runtime and .NET Framework 4.5.1.NET Framework 4.5.1

在中適用於 Windows 8.x 市集應用程式的 .NET.NET for Windows 8.x Store apps,某些例外狀況資訊通常會在透過 non-.NET Framework 堆疊框架傳播例外狀況時遺失。 Windows 8Windows 8In 適用於 Windows 8.x 市集應用程式的 .NET.NET for Windows 8.x Store apps for Windows 8Windows 8, some exception information is typically lost when an exception is propagated through non-.NET Framework stack frames. .NET Framework 4.5.1.NET Framework 4.5.1從和Windows 8.1Windows 8.1開始,通用語言執行平臺會繼續使用所擲回Exception的原始物件,除非在 non-.NET Framework 堆疊框架中修改該例外狀況。Starting with the .NET Framework 4.5.1.NET Framework 4.5.1 and Windows 8.1Windows 8.1, the common language runtime continues to use the original Exception object that was thrown unless that exception was modified in a non-.NET Framework stack frame.

建構函式

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

初始化 Exception 類別的新執行個體。Initializes a new instance of the Exception class.

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

使用序列化資料,初始化 Exception 類別的新執行個體。Initializes a new instance of the Exception class with serialized data.

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

使用指定的錯誤訊息,初始化 Exception 類別的新執行個體。Initializes a new instance of the Exception class with a specified error message.

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

使用指定的錯誤訊息以及造成此例外狀況的內部例外狀況的參考,初始化 Exception 類別的新執行個體。Initializes a new instance of the Exception class with a specified error message and a reference to the inner exception that is the cause of this exception.

屬性

Data Data Data Data

取得提供例外狀況之其他使用者定義相關資訊的索引鍵/值組集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

HelpLink HelpLink HelpLink HelpLink

取得或設定與這個例外狀況相關聯的說明檔連結。Gets or sets a link to the help file associated with this exception.

HResult HResult HResult HResult

取得或設定 HRESULT,它是指派給特定例外狀況的編碼數值。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

InnerException InnerException InnerException InnerException

取得造成目前例外狀況的 Exception 執行個體。Gets the Exception instance that caused the current exception.

Message Message Message Message

取得描述目前例外狀況的訊息。Gets a message that describes the current exception.

Source Source Source Source

取得或設定造成錯誤的應用程式或物件的名稱。Gets or sets the name of the application or the object that causes the error.

StackTrace StackTrace StackTrace StackTrace

取得呼叫堆疊上即時運算框架的字串表示。Gets a string representation of the immediate frames on the call stack.

TargetSite TargetSite TargetSite TargetSite

取得擲回目前例外狀況的方法。Gets the method that throws the current exception.

方法

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

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

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

在衍生類別中覆寫時,傳回一或多個後續的例外狀況的根本原因 ExceptionWhen 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 的淺層複本 (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.

適用於

另請參閱