throw (C# Başvurusu)
Programın yürütülmesi sırasında bir özel durumun oluşumunu bildirir.
Açıklamalar
Sözdizimi şöyledir throw :
throw [e];
Burada e türetilmiş bir sınıfın örneğidir System.Exception . Aşağıdaki örnek, throw IndexOutOfRangeException adlı bir metoda geçirilen bağımsız değişken GetNumber iç dizinin geçerli bir dizinine karşılık gelmiyorsa bir oluşturmak için ifadesini kullanır.
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];
}
}
Yöntem çağıranları, sonra try-catch try-catch-finally oluşturulan özel durumu işlemek için bir veya bloğu kullanır. Aşağıdaki örnek, yöntemi tarafından oluşturulan özel durumu işler 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
Özel durum yeniden oluşturuluyor
throw , catch bir blokta işlenen bir özel durumu yeniden oluşturmak için bir blokta da kullanılabilir catch . Bu durumda, throw bir özel durum işleneni almaz. Bir yöntem çağıran bir bağımsız değişkende diğer bir kitaplık yöntemine geçtiğinde ve kitaplık yöntemi çağırana geçirilmesi gereken bir özel durum oluşturduğunda, en çok yararlı olur. Örneğin, aşağıdaki örnek, NullReferenceException başlatılmamış bir dizenin ilk karakterini almaya çalışırken oluşturulan bir öğesini yeniden atar.
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()
Önemli
Ayrıca, throw e catch çağrıyı yapana geçirdiğiniz yeni bir özel durum oluşturmak için bir blokta söz dizimini kullanabilirsiniz. Bu durumda, özelliğinden erişilebilen özgün özel durumun yığın izlemesi StackTrace korunmaz.
throwİfade
C# 7,0 ' den itibaren bir deyim ve throw deyim olarak kullanılabilir. Bu, daha önce desteklenmeyen bağlamlarda bir özel durumun oluşturulmasına olanak sağlar. Bu modüller şunlardır:
koşullu işleç. Aşağıdaki örnek, bir
throwArgumentException Yöntem boş bir dize dizisi geçirtiyse, oluşturmak için bir ifade kullanır. C# 7,0 ' den önce, bu mantığın bir bildirimde görünmesi gerekirif/else.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 birleşim işleci. Aşağıdaki örnekte bir
throwifade, bir özelliğe atanmış dize ise bir özel durum oluşturmak için null birleşim işleciyle birlikte kullanılırNamenull.public string Name { get => name; set => name = value ?? throw new ArgumentNullException(paramName: nameof(value), message: "Name cannot be null"); }ifade-Bodied lambda veya yöntem. Aşağıdaki örnek, bir InvalidCastException değere dönüştürme desteklenmediğinden bir ifade-Bodied yöntemi gösterir DateTime .
DateTime ToDateTime(IFormatProvider provider) => throw new InvalidCastException("Conversion to a DateTime is not supported.");
C# dili belirtimi
Daha fazla bilgi edinmek için, bkz. C# Dil Belirtimi. Dil belirtimi, C# sözdizimi ve kullanımı için kesin bir kaynaktır.