La instrucción throw se utiliza para señalizar la aparición de una situación anómala (excepción) durante la ejecución del programa.
La excepción producida es un objeto cuya clase se deriva de System.Exception, por ejemplo:
class MyException : System.Exception {} // ... throw new MyException();
Normalmente, la instrucción throw se utiliza con las instrucciones try-catch o try-finally. Cuando se produce una excepción, el programa busca la instrucción catch que controla esa excepción.
También se puede volver a producir una excepción detectada mediante la instrucción throw. Para obtener más información, incluidos ejemplos, vea try-catch e Producir excepciones.
Este ejemplo muestra cómo provocar una excepción mediante la instrucción throw.
// throw example using System; public class ThrowTest { static void Main() { string s = null; if (s == null) { throw new ArgumentNullException(); } Console.Write("The string s is null"); // not executed } }
Se produce la excepción ArgumentNullException.
Vea los ejemplos de try-catch, try-finally y try-catch-finally.
Para obtener más información, vea las secciones siguientes de Especificación del lenguaje C#.
5.3.3.11 Instrucciones throw
8.9.5 La instrucción throw