在 .NET 中處理和擲回例外狀況Handling and throwing exceptions in .NET

應用程式必須能以一致的方式處理執行期間發生的錯誤。Applications must be able to handle errors that occur during execution in a consistent manner. .NET 提供模型,可以統一的方式通知應用程式的錯誤:.NET 作業會藉由擲回例外狀況指出失敗。.NET provides a model for notifying applications of errors in a uniform way: .NET operations indicate failure by throwing exceptions.

例外狀況Exceptions

例外狀況是執行程式所遇到的錯誤狀況或未預期的行為。An exception is any error condition or unexpected behavior that is encountered by an executing program. 在發生程式碼或您呼叫的程式碼 (例如共用程式庫) 中有錯誤、無法使用作業系統資源、執行階段遇到非預期的狀況 (例如無法驗證的程式碼) 等情況時,就可能會擲回例外狀況。Exceptions can be thrown because of a fault in your code or in code that you call (such as a shared library), unavailable operating system resources, unexpected conditions that the runtime encounters (such as code that can't be verified), and so on. 您的應用程式可從一些狀況中復原,但有些狀況就無法復原。Your application can recover from some of these conditions, but not from others. 雖然您可以從大部分的應用程式例外狀況中復原,但是無法從大部分的執行階段例外狀況中復原。Although you can recover from most application exceptions, you can't recover from most runtime exceptions.

在 .NET 中,例外狀況是繼承自 System.Exception 類別的物件。In .NET, an exception is an object that inherits from the System.Exception class. 從發生問題的程式碼區域擲回例外狀況。An exception is thrown from an area of code where a problem has occurred. 例外狀況會向上傳遞堆疊,直到應用程式處理或程式終止它。The exception is passed up the stack until the application handles it or the program terminates.

例外狀況與傳統錯誤處理方法的比較Exceptions vs. traditional error-handling methods

傳統上,一種語言的錯誤處理模型不是依賴語言唯一偵測錯誤的方式與尋找處理常式,就是依賴作業系統所提供的錯誤處理機制。Traditionally, a language's error-handling model relied on either the language's unique way of detecting errors and locating handlers for them, or on the error-handling mechanism provided by the operating system. .NET 實作例外狀況處理的方式具有下列優點:The way .NET implements exception handling provides the following advantages:

  • .NET 程式語言擲回和處理例外狀況的方式都相同。Exception throwing and handling works the same for .NET programming languages.

  • 不需要任何特定語言語法以處理例外狀況,但可讓每一種語言定義屬於自己的語法。Doesn't require any particular language syntax for handling exceptions, but allows each language to define its own syntax.

  • 例外狀況可跨處理序,甚至是跨電腦界限擲回。Exceptions can be thrown across process and even machine boundaries.

  • 可將例外狀況處理程式碼加入應用程式,以增加程式可靠性。Exception-handling code can be added to an application to increase program reliability.

例外狀況優於其他錯誤通知方法,例如傳回碼。Exceptions offer advantages over other methods of error notification, such as return codes. 不會發生未注意到失敗的情況,因為如果系統擲出例外狀況且您未加以處理,執行階段就會終止您的應用程式。Failures don't go unnoticed because if an exception is thrown and you don't handle it, the runtime terminates your application. 無效值不會因為程式碼無法檢查失敗傳回碼,而持續在系統中散佈。Invalid values don't continue to propagate through the system as a result of code that fails to check for a failure return code.

常見的例外狀況Common exceptions

下表列出一些常見的例外狀況,並提供可能造成這些例外狀況的原因範例。The following table lists some common exceptions with examples of what can cause them.

例外狀況類型Exception type 說明Description 範例Example
Exception 適用於所有例外狀況的基底類別。Base class for all exceptions. 無 (使用這個例外狀況的衍生類別)。None (use a derived class of this exception).
IndexOutOfRangeException 只有當陣列索引不正確時,才由執行階段擲回。Thrown by the runtime only when an array is indexed improperly. 在陣列有效範圍之外對它進行索引:Indexing an array outside its valid range:
arr[arr.Length+1]
NullReferenceException 只有當參考 Null 物件時,才由執行階段擲回。Thrown by the runtime only when a null object is referenced. object o = null;
o.ToString();
InvalidOperationException 當處於無效狀態時,由方法擲回。Thrown by methods when in an invalid state. 在從基礎集合將項目移除之後,呼叫 Enumerator.MoveNext()Calling Enumerator.MoveNext() after removing an item from the underlying collection.
ArgumentException 適用於所有引數例外狀況的基底類別。Base class for all argument exceptions. 無 (使用這個例外狀況的衍生類別)。None (use a derived class of this exception).
ArgumentNullException 由不允許引數為 Null 的方法擲回。Thrown by methods that do not allow an argument to be null. String s = null;
"Calculate".IndexOf(s);
ArgumentOutOfRangeException 由驗證引數是在指定範圍內的方法擲回。Thrown by methods that verify that arguments are in a given range. String s = "string";
s.Substring(s.Length+1);

另請參閱See also