Share via


Como: Lançar exceções explicitamente

Você pode lançar uma exceção explicitamente usando a instrução throw.Você também pode lançar novamente uma exceção capturada usando a instrução throw.É uma prática de codificação recomendável adicionar informações a uma exceção que é lançada novamente para fornecer mais informações durante a depuração.

O exemplo de código a seguir usa um bloco try/catch para capturar uma possível FileNotFoundException.Após o bloco Try está um bloco catch que captura a FileNotFoundException e grava uma mensagem do console se não for encontrado o arquivo de dados.A próxima instrução é a instrução throw que gera uma nova FileNotFoundException e adiciona as informações de texto para a exceção.

Exemplo

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();
      }
   }
}

Consulte também

Tarefas

Como: Use o bloco try/catch para interceptar exceções

Como: Usar exceções específicas em um bloco Catch

Como: Uso Finally bloqueia

Outros recursos

Fundamentos da Manipulação de Exceções