throw (C# 參考)throw (C# Reference)

在程式執行期間發出出現例外狀況的訊號。Signals the occurrence of an exception during program execution.

備註Remarks

throw 的語法為:The syntax of throw is:

throw [e];

e 是衍生自 System.Exception 之類別的執行個體。where e is an instance of a class derived from System.Exception. 如果傳遞給 GetNumber 方法的引數未對應至內部陣列的有效索引,則下列範例會使用 throw 陳述式來擲回 IndexOutOfRangeExceptionThe following example uses the throw statement to throw an IndexOutOfRangeException if the argument passed to a method named GetNumber does not correspond to a valid index of an internal array.

using System;

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-catchtry-catch-finally 區塊來處理所擲回的例外狀況。Method callers then use a try-catch or try-catch-finally block to handle the thrown exception. 下列範例會處理 GetNumber 方法所擲回的例外狀況。The following example handles the exception thrown by the GetNumber method.

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

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

throw 也可以用於 catch 區塊,以重新擲回 catch 區塊中所處理的例外狀況。throw can also be used in a catch block to re-throw an exception handled in a catch block. 在此情況下,throw 陳述式不接受例外狀況運算元。In this case, throw does not take an exception operand. 這最適用於當方法將來自呼叫端的引數傳遞給某個其他程式庫方法,且程式庫方法擲回必須傳遞給呼叫端的例外狀況時。It is most useful when a method passes on an argument from a caller to some other library method, and the library method throws an exception that must be passed on to the caller. 例如,下列範例會重新擲回 NullReferenceException,而這是在嘗試擷取未初始化字串的第一個字元時擲回。For example, the following example re-throws an NullReferenceException that is thrown when attempting to retrieve the first character of an uninitialized string.

using System;

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 語法,來具現化傳遞給呼叫端的新例外狀況。You can also use the throw e syntax in a catch block to instantiate a new exception that you pass on to the caller. 在此情況下,不會保留原始例外狀況的堆疊追蹤 (可從 StackTrace 屬性取得)。In this case, the stack trace of the original exception, which is available from the StackTrace property, is not preserved.

throw 運算式The throw expression

從 C# 7.0 開始,throw 可以用作運算式和陳述式。Starting with C# 7.0, throw can be used as an expression as well as a statement. 這可在先前不支援的內容中擲回例外狀況。This allows an exception to be thrown in contexts that were previously unsupported. 它們包括:These include:

  • 條件運算子the conditional operator. 如果將空字串陣列傳遞給方法,則下列範例會使用 throw 運算式來擲回 ArgumentExceptionThe following example uses a throw expression to throw an ArgumentException if a method is passed an empty string array. 在 C# 7.0 之前,這個邏輯必須出現在 if/else 陳述式中。Before C# 7.0, this logic would need to appear in an if/else statement.

    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 聯合運算子the null-coalescing operator. 在下列範例中,如果指派給 Name 屬性的字串是 null,則搭配使用 throw 運算式與 Null 聯合運算子會擲回例外狀況。In the following example, a throw expression is used with a null-coalescing operator to throw an exception if the string assigned to a Name property is null.

    public string Name
    {
        get => name;
        set => name = value ?? 
            throw new ArgumentNullException(paramName: nameof(value), message: "Name cannot be null");
    }   
    
  • 運算式主體 ambda 或方法。an expression-bodied lambda or method. 下列範例說明因不支援轉換為 DateTime 值而擲回 InvalidCastException 的運算式主體方法。The following example illustrates an expression-bodied method that throws an InvalidCastException because a conversion to a DateTime value is not supported.

    DateTime ToDateTime(IFormatProvider provider) => 
             throw new InvalidCastException("Conversion to a DateTime is not supported.");
    

C# 語言規格C# language specification

如需詳細資訊,請參閱<C# 語言規格>。For more information, see the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

請參閱See also