throw (référence C#)throw (C# Reference)
Signale l’occurrence d’une exception pendant l’exécution du programme.Signals the occurrence of an exception during program execution.
RemarquesRemarks
La syntaxe de throw
est :The syntax of throw
is:
throw [e];
où e
est une instance d’une classe dérivée de System.Exception.where e
is an instance of a class derived from System.Exception. L’exemple suivant utilise l’instruction throw
pour lever une exception IndexOutOfRangeException si l’argument passé à une méthode nommée GetNumber
ne correspond pas à un index valide d’un tableau interne.The 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];
}
}
Les appelants de méthode utilisent alors un bloc try-catch
ou try-catch-finally
pour gérer l’exception levée.Method callers then use a try-catch
or try-catch-finally
block to handle the thrown exception. L’exemple suivant gère l’exception levée par la méthode 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
Exception levée plusieurs foisRe-throwing an exception
throw
peut également être utilisé dans un bloc catch
pour lever de nouveau une exception gérée dans un bloc catch
.throw
can also be used in a catch
block to re-throw an exception handled in a catch
block. Dans ce cas, throw
n’accepte pas d’opérande d’exception.In this case, throw
does not take an exception operand. Cela est très utile lorsqu’une méthode passe un argument d’un appelant à une autre méthode de bibliothèque, et que la méthode de bibliothèque lève une exception qui doit être passée à l’appelant.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. Par exemple, l’exemple suivant lève de nouveau une exception NullReferenceException qui est levée lorsque vous tentez de récupérer le premier caractère d’une chaîne non initialisée.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()
Important
Vous pouvez également utiliser la syntaxe throw e
dans un bloc catch
pour instancier une nouvelle exception que vous passez à l’appelant.You can also use the throw e
syntax in a catch
block to instantiate a new exception that you pass on to the caller. Dans ce cas, la trace de la pile de l’exception d’origine, qui est disponible à partir de la propriété StackTrace, n’est pas conservée.In this case, the stack trace of the original exception, which is available from the StackTrace property, is not preserved.
Expression throw
The throw
expression
À compter de C# 7.0, throw
peut être utilisé comme expression et comme instruction.Starting with C# 7.0, throw
can be used as an expression as well as a statement. Ainsi, une exception peut être levée dans des contextes qui n’étaient précédemment pas pris en charge.This allows an exception to be thrown in contexts that were previously unsupported. notamment :These include:
opérateur conditionnel.the conditional operator. l’exemple suivant utilise une expression
throw
pour lever une exception ArgumentException si une méthode reçoit un tableau de chaînes vide.The following example uses athrow
expression to throw an ArgumentException if a method is passed an empty string array. Avant C# 7.0, cette logique devait figurer dans une instructionif
/else
.Before C# 7.0, this logic would need to appear in anif
/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."); }
l’opérateur de fusion de Null :the null-coalescing operator. dans l’exemple suivant, une expression
throw
est utilisée avec un opérateur de fusion de Null pour lever une exception si la chaîne assignée à une propriétéName
estnull
.In the following example, athrow
expression is used with a null-coalescing operator to throw an exception if the string assigned to aName
property isnull
.public string Name { get => name; set => name = value ?? throw new ArgumentNullException(paramName: nameof(value), message: "Name cannot be null"); }
un lambda ou une méthode expression-bodied :an expression-bodied lambda or method. l’exemple suivant illustre une méthode expression-bodied qui lève une exception InvalidCastException, car une conversion vers une valeur DateTime n’est pas prise en charge.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.");
spécification du langage C#C# language specification
Pour plus d'informations, voir la spécification du langage C#.For more information, see the C# Language Specification. La spécification du langage est la source de référence pour la syntaxe C# et son utilisation.The language specification is the definitive source for C# syntax and usage.