Cómo: Iniciar excepciones explícitamente

Actualización: noviembre 2007

Una excepción se puede producir de manera explícita mediante la instrucción throw. También se puede producir de nuevo una excepción detectada mediante la instrucción throw. Cuando se escribe código, resulta muy recomendable agregar información a una excepción que se produce de nuevo para proporcionar más información durante el proceso de depuración.

En el ejemplo de código siguiente se usa un bloque try/catch para detectar una posible excepción FileNotFoundException. Después del bloque Try hay un bloque Catch que detecta FileNotFoundException y escribe un mensaje en la consola si no se encuentra el archivo de datos. La siguiente instrucción es una instrucción Throw que produce una nueva excepción FileNotFoundException y agrega información de texto a la excepción.

Ejemplo

Option Strict On

Imports System
Imports System.IO

Public Class ProcessFile

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

          'A value is read from the file and output to the console.
          line = sr.ReadLine()
          Console.WriteLine(line)
      Catch e As FileNotFoundException
          Console.WriteLine("[Data File Missing] {0}", 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 
using System;
using System.IO;

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

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

Vea también

Tareas

Cómo: Utilizar el bloque Try/Catch para detectar excepciones

Cómo: Utilizar excepciones específicas en un bloque Catch

Cómo: Utilizar bloques Finally

Otros recursos

Fundamentos del control de excepciones