throw (Referencia de C#)throw (C# Reference)
Indica la aparición de una excepción durante la ejecución del programa.Signals the occurrence of an exception during program execution.
ComentariosRemarks
La sintaxis de throw
es la siguiente:The syntax of throw
is:
throw [e];
donde e
es una instancia de una clase derivada de System.Exception.where e
is an instance of a class derived from System.Exception. En el ejemplo siguiente se usa la instrucción throw
para producir una excepción IndexOutOfRangeException si el argumento pasado a un método denominado GetNumber
no se corresponde con un índice válido de una matriz interna.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];
}
}
Después, los autores de llamadas a método usan un bloque try-catch
o try-catch-finally
para controlar la excepción generada.Method callers then use a try-catch
or try-catch-finally
block to handle the thrown exception. En el ejemplo siguiente se controla la excepción producida por el método 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
Volver a iniciar una excepciónRe-throwing an exception
throw
también se puede usar en un bloque catch
para volver a iniciar una excepción controlada en un bloque catch
.throw
can also be used in a catch
block to re-throw an exception handled in a catch
block. En este caso, throw
no toma un operando de excepción.In this case, throw
does not take an exception operand. Resulta más útil cuando un método pasa un argumento de un autor de llamada a otro método de biblioteca y el método de biblioteca produce una excepción que se debe pasar al autor de llamada.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. Por ejemplo, en el ejemplo siguiente se vuelve a iniciar una excepción NullReferenceException que se produce al intentar recuperar el primer carácter de una cadena sin inicializar.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()
Importante
También puede usar la sintaxis throw e
en un bloque catch
para crear instancias de una nueva excepción que se pase al autor de llamada.You can also use the throw e
syntax in a catch
block to instantiate a new exception that you pass on to the caller. En este caso, no se conserva el seguimiento de la pila de la excepción original, que está disponible en la propiedad StackTrace.In this case, the stack trace of the original exception, which is available from the StackTrace property, is not preserved.
La expresión throw
The throw
expression
A partir de C# 7.0, se puede usar throw
como una expresión y como una instrucción.Starting with C# 7.0, throw
can be used as an expression as well as a statement. Esto permite iniciar una excepción en contextos que antes no se admitían.This allows an exception to be thrown in contexts that were previously unsupported. Se incluyen los siguientes:These include:
El operador condicional.the conditional operator. En el ejemplo siguiente se usa una expresión
throw
para iniciar una excepción ArgumentException si se pasa a un método una matriz de cadena vacía.The following example uses athrow
expression to throw an ArgumentException if a method is passed an empty string array. Antes de C# 7.0, esta lógica tenía que aparecer en una instrucciónif
/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."); }
El operador de uso combinado de NULL.the null-coalescing operator. En el ejemplo siguiente, se usa una expresión
throw
con un operador de uso combinado de NULL para producir una excepción si la cadena asignada a una propiedadName
esnull
.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 método o lambda con forma de expresión.an expression-bodied lambda or method. En el ejemplo siguiente se muestra un método con forma de expresión que produce una excepción InvalidCastException porque no se admite una conversión a un valor DateTime.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.");
Especificación del lenguaje C#C# language specification
Para obtener más información, consulte la Especificación del lenguaje C#.For more information, see the C# Language Specification. La especificación del lenguaje es la fuente definitiva de la sintaxis y el uso de C#.The language specification is the definitive source for C# syntax and usage.
Vea tambiénSee also
Comentarios
Cargando comentarios...