Referencia del lenguaje C#
try-catch-finally (Referencia de C#)

Un uso común de catch y finally consiste en obtener y utilizar recursos en un bloque try, tratar circunstancias excepcionales en el bloque catch y liberar los recursos en el bloque finally.

Para obtener más información y ejemplos sobre cómo volver a producir las excepciones, vea try-catch y Producir excepciones.

Ejemplo

// try_catch_finally.cs
using System;
public class EHClass
{
    static void Main()
    {
        try
        {
            Console.WriteLine("Executing the try statement.");
            throw new NullReferenceException();
        }
        catch (NullReferenceException e)
        {
            Console.WriteLine("{0} Caught exception #1.", e);
        }
        catch
        {
            Console.WriteLine("Caught exception #2.");
        }
        finally
        {
            Console.WriteLine("Executing finally block.");
        }
    }
}

Resultados del ejemplo

Executing the try statement.
System.NullReferenceException: Object reference not set to an instance of an object.
   at EHClass.Main() Caught exception #1.
Executing finally block.
Especificación del lenguaje C#

Para obtener más información, vea las secciones siguientes de Especificación del lenguaje C#.

  • 5.3.3.15 Instrucciones Try-catch-finally

  • 8.10 La instrucción try

  • 16 Excepciones

Vea también

Tareas

Cómo: Iniciar excepciones explícitamente

Referencia

Palabras clave de C#
The try, catch, and throw Statements
Instrucciones para el control de excepciones (Referencia de C#)
throw (Referencia de C#)

Conceptos

Guía de programación de C#

Otros recursos

Referencia de C#

Etiquetas :


Page view tracker