throw (C# 參考)
在程式執行期間發出出現例外狀況的訊號。
備註
throw
的語法為:
throw [e];
而 e
是衍生自 System.Exception 之類別的執行個體。 如果傳遞給 GetNumber
方法的引數未對應至內部陣列的有效索引,則下列範例會使用 throw
陳述式來擲回 IndexOutOfRangeException 。
using System;
namespace Throw2
{
public class NumberGenerator
{
int[] numbers = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
public int GetNumber(int index)
{
if (index < 0 || index >= numbers.Length)
{
throw new IndexOutOfRangeException();
}
return numbers[index];
}
}
方法呼叫端接著會使用 try-catch
或 try-catch-finally
區塊來處理所擲回的例外狀況。 下列範例會處理 GetNumber
方法所擲回的例外狀況。
using System;
public class Example
{
public static void Main()
{
var gen = new NumberGenerator();
int index = 10;
try
{
int value = gen.GetNumber(index);
Console.WriteLine($"Retrieved {value}");
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine($"{e.GetType().Name}: {index} is outside the bounds of the array");
}
}
}
// The example displays the following output:
// IndexOutOfRangeException: 10 is outside the bounds of the array
重新擲回例外狀況
throw
也可以用於 catch
區塊,以重新擲回 catch
區塊中所處理的例外狀況。 在此情況下,throw
陳述式不接受例外狀況運算元。 這最適用於當方法將來自呼叫端的引數傳遞給某個其他程式庫方法,且程式庫方法擲回必須傳遞給呼叫端的例外狀況時。 例如,下列範例會重新擲回 NullReferenceException,而這是在嘗試擷取未初始化字串的第一個字元時擲回。
using System;
namespace Throw
{
public class Sentence
{
public Sentence(string s)
{
Value = s;
}
public string Value { get; set; }
public char GetFirstCharacter()
{
try
{
return Value[0];
}
catch (NullReferenceException e)
{
throw;
}
}
}
public class Example
{
public static void Main()
{
var s = new Sentence(null);
Console.WriteLine($"The first character is {s.GetFirstCharacter()}");
}
}
// The example displays the following output:
// Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
// at Sentence.GetFirstCharacter()
// at Example.Main()
重要
您也可以使用 catch
區塊中的 throw e
語法,來具現化傳遞給呼叫端的新例外狀況。 在此情況下,不會保留原始例外狀況的堆疊追蹤 (可從 StackTrace 屬性取得)。
throw
運算式
throw
可以當做運算式和 語句使用。 這可在先前不支援的內容中擲回例外狀況。 其中包含:
條件運算子。 如果將空字串陣列傳遞給方法,則下列範例會使用
throw
運算式來擲回 ArgumentException。private static void DisplayFirstNumber(string[] args) { string arg = args.Length >= 1 ? args[0] : throw new ArgumentException("You must supply an argument"); if (Int64.TryParse(arg, out var number)) Console.WriteLine($"You entered {number:F0}"); else Console.WriteLine($"{arg} is not a number."); }
Null 聯合運算子。 在下列範例中,如果指派給
Name
屬性的字串是null
,則搭配使用throw
運算式與 Null 聯合運算子會擲回例外狀況。public string Name { get => name; set => name = value ?? throw new ArgumentNullException(paramName: nameof(value), message: "Name cannot be null"); }
運算式主體 ambda 或方法。 下列範例說明因不支援轉換為 DateTime 值而擲回 InvalidCastException 的運算式主體方法。
DateTime ToDateTime(IFormatProvider provider) => throw new InvalidCastException("Conversion to a DateTime is not supported.");
C# 語言規格
如需詳細資訊,請參閱 C# 語言規格。 語言規格是 C# 語法及用法的限定來源。