throw (C# 參考)

throw 陳述式用來表示在程式執行期間異常情況 (例外狀況) 的發生。

備註

擲回的例外狀況是其類別衍生自 System.Exception 的物件,如下列範例所示。

class MyException : System.Exception {}
// ...
throw new MyException();

throw 陳述式通常都會與 try-catch 或 try-finally 陳述式一起使用。 如需詳細資訊與範例,請參閱 try-catch (C# 參考)HOW TO:明確擲回例外狀況

範例

這個範例說明如何使用 throw 陳述式擲回例外狀況。

    public class ThrowTest2
    {

        static int GetNumber(int index)
        {
            int[] nums = { 300, 600, 900 };
            if (index > nums.Length)
            {
                throw new IndexOutOfRangeException();
            }
            return nums[index];

        }
        static void Main() 
        {
            int result = GetNumber(3);

        }
    }
    /*
        Output:
        The System.IndexOutOfRangeException exception occurs.
    */

程式碼範例

請參閱 try-catch (C# 參考)HOW TO:明確擲回例外狀況 中的範例。

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格。 語言規格是 C# 語法和用法的決定性來源。

請參閱

工作

HOW TO:明確擲回例外狀況

參考

try-catch (C# 參考)

C++ 中的 try、catch 和 throw 陳述式

C# 關鍵字

例外處理陳述式 (C# 參考)

概念

C# 程式設計手冊

其他資源

C# 參考