Comment : lever explicitement des exceptions

Mise à jour : novembre 2007

Vous pouvez lever explicitement une exception à l'aide de l'instruction throw. Vous pouvez aussi lever de nouveau une exception interceptée à l'aide de l'instruction throw. L'ajout d'informations à une exception qui est levée de nouveau pour fournir un complément d'information lors du débogage constitue une bonne pratique de programmation.

L'exemple de code suivant utilise un bloc try/catch pour intercepter une exception FileNotFoundException possible. Le bloc try est suivi d'un bloc catch qui intercepte FileNotFoundExceptionet copie un message vers la console si le fichier de données est introuvable. L'instruction suivante est l'instruction throw qui lève de nouveau FileNotFoundException et ajoute des informations de texte à l'exception.

Exemple

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

Voir aussi

Tâches

Comment : utiliser le bloc try/catch pour intercepter des exceptions

Comment : utiliser des exceptions spécifiques dans un bloc catch

Comment : utiliser des blocs finally

Autres ressources

Notions de base de la gestion des exceptions