Cómo iniciar excepciones explícitamenteHow to explicitly throw exceptions

Puede iniciar explícitamente una excepción mediante la instrucción throw de C# o la instrucción Throw de Visual Basic.You can explicitly throw an exception using the C# throw or the Visual Basic Throw statement. También se puede iniciar una excepción detectada usando de nuevo la instrucción throw.You can also throw a caught exception again using the throw statement. En diseño de código, es recomendable agregar información a una excepción que se vuelve a iniciar para proporcionar más información durante la depuración.It is good coding practice to add information to an exception that is re-thrown to provide more information when debugging.

En el siguiente ejemplo de código se usa un bloque try/catch para detectar una posible FileNotFoundException.The following code example uses a try/catch block to catch a possible FileNotFoundException. Seguido del bloque try va un bloque catch que detecta FileNotFoundException y escribe un mensaje a la consola si no se encuentra el archivo de datos.Following the try block is a catch block that catches the FileNotFoundException and writes a message to the console if the data file is not found. La siguiente instrucción es throw que inicia un parámetro FileNotFoundException nuevo y agrega información de texto a la excepción.The next statement is the throw statement that throws a new FileNotFoundException and adds text information to the exception.

using System;
using System.IO;

public class ProcessFile
{
    public static void Main()
    {
        FileStream fs;
        try
        {
            // Opens a text tile.
            fs = new FileStream(@"C:\temp\data.txt", FileMode.Open);
            var sr = new StreamReader(fs);

            // A value is read from the file and output to the console.
            string line = sr.ReadLine();
            Console.WriteLine(line);
        }
        catch(FileNotFoundException e)
        {
            Console.WriteLine($"[Data File Missing] {e}");
            throw new FileNotFoundException(@"[data.txt not in c:\temp directory]", e);
        }
        finally
        {
            if (fs != null)
                fs.Close();
        }
    }
}
Option Strict On

Imports System.IO

Public Class ProcessFile

    Public Shared Sub Main()
        Dim fs As FileStream
        Try
            ' Opens a text file.
            fs = New FileStream("c:\temp\data.txt", FileMode.Open)
            Dim sr As New StreamReader(fs)

            ' A value is read from the file and output to the console.
            Dim line As String = sr.ReadLine()
            Console.WriteLine(line)
        Catch e As FileNotFoundException
            Console.WriteLine($"[Data File Missing] {e}")
            Throw New FileNotFoundException("[data.txt not in c:\temp directory]", e)
        Finally
            If fs IsNot Nothing Then fs.Close()
        End Try
    End Sub
End Class

Vea tambiénSee also