Page d'Accueil

Manipulation de l'exception dans le traitement de fichier

 

finally

Jusqu'ici, pour manipuler les exceptions, nous utilisions les mots-clés try, catch, et throw. Ceux-ci nous ont permis d'effectuer des tâches normales dans une section try et puis de manipuler une exception, le cas échéant, dans un bloc catch.

Dans la leçon précédente, nous avons mentionné que, quand vous créez un stream, le logiciel d'exploitation doit allouer des ressources et les consacrer aux opérations de traitement de fichier. Des ressources additionnelles peuvent être fournies à l'objet qui en charge d'écrire, ou  de lire dans le stream. Nous avons également vu que, quand le streaming prenait fin, nous devrions libérer les ressources et les remettre de nouveau au logiciel d'exploitation. Pour ce faire, nous avons appelé la méthode close() de la variable qui utilisait les ressources.

Plus que n'importe quelle autre tâche, le traitement de fichier est principalement dans le besoin de la manipulation d'exception. Comme nous verrons dans la prochaine section, pandant le traitement de fichier, il y a beaucoup de choses qui peuvent tourner mal. Pour cette raison, la création et/ou la gestion des stream devraient être exécutées dans un bloc try pour être prêtes pour manipuler les exceptions qui se produiraient. En plus de manipuler réellement les exceptions, le langage C# fournit un mot-clé spécial des ressources libres utilisées. Ce mot-clé est finally.

Finalement le mot-clé est utilisé pour créer une section d'une exception. Comme catch, le bloc finally ne peut pas exister par lui-même. Il peut être créé après une section try. La formule utilisée serait :

try
{
}
finally
{
}

Basé sur ceci, la section finally a son propre corps, délimité par ses accolades. Comme catch, la section finaly est créée après la section try. À la différence que catch, n'a finalement jamais de parenthèses et ne prend jamais des arguments. À la différence de catch, la section finally  est toujours exécutée. Puisque la clause finally est toujours exécutée, vous pouvez y inclure n'importe quel type de code mais il est habituellement approprié de libérer les ressources qui ont été allouées plus tôt. Voici un exemple :

using System;
using System.IO;

public class Program
{
    static int Main(string[] args)
    {
        string NameOfFile = "Members.clb";
	
        FileStream fstPersons = new FileStream(NameOfFile, FileMode.Create);
        BinaryWriter wrtPersons = new BinaryWriter(fstPersons);
        
        try 
        {
            wrtPersons.Write("James Bloch");
            wrtPersons.Write("Catherina Wallace");
            wrtPersons.Write("Bruce Lamont");
            wrtPersons.Write("Douglas Truth");
        }
        finally
        {
            wrtPersons.Close();
            fstPersons.Close();
        }

        return 0;
    }
}

De la même manière, vous pouvez employer finalement une section pour libérer des ressources utilisées en lisant d'un jet :

using System;
using System.IO;

public class Program
{
    static int Main(string[] args)
    {
/*        string NameOfFile = "Members.clb";
	
        FileStream fstPersons = new FileStream(NameOfFile, FileMode.Create);
        BinaryWriter wrtPersons = new BinaryWriter(fstPersons);
        
        try 
        {
            wrtPersons.Write("James Bloch");
            wrtPersons.Write("Catherina Wallace");
            wrtPersons.Write("Bruce Lamont");
            wrtPersons.Write("Douglas Truth");
        }
        finally
        {
            wrtPersons.Close();
            fstPersons.Close();
        }*/
        
        string NameOfFile = "Members.clb";
        string strLine = null;
        
        FileStream fstMembers = new FileStream(NameOfFile, FileMode.Open);
        BinaryReader rdrMembers = new BinaryReader(fstMembers);

        try
        {
            strLine = rdrMembers.ReadString();
            Console.WriteLine(strLine);
            strLine = rdrMembers.ReadString();
            Console.WriteLine(strLine);
            strLine = rdrMembers.ReadString();
            Console.WriteLine(strLine);
            strLine = rdrMembers.ReadString();
            Console.WriteLine(strLine);
        }
        finally
        {
            rdrMembers.Close();
            fstMembers.Close();
        }

        return 0;
    }
}

Naturellement, puisque la totalité du bloc de code commence par une section try, il est utilisé pour la manipulation d'exception. Ceci signifie que vous pouvez ajouter des sections catch nécessaires et appropriées mais vous ne le devez pas .

Étude pratiqueÉtude pratique : Libérer enfin des ressources

  1. Commencez Microsoft Visual C# et créez une application de console appelée IceCream4
  2. Sauvegardez le projet, sur la barre d'outils standard, cliquez le bouton sauvegarder tout Économiser tous
  3. Changez le nom de solution en VendingMachine4
  4. Acceptez le nom du projet comme IceCream3 et cliquez Sauvegarder
  5. Pour créer une nouvelle classe, sur le menu principal, cliquez projet - > Ajouter la classe…
  6. Placez le nom IceScream et cliquez Ajouter
  7. Changez le fichier comme suit :
     
    using System;
    using System.IO;
    
    namespace IceCream4
    {
        delegate void Request();
    
        // This class is used to create and manage an ice scream
        // and to process an order
        public sealed class IceCream
        {
            // This is the base price of an ice scream
            // Optional values may be added to it
            public const decimal BasePrice = 1.55M;
    
            // These arrays are used to build the components 
            // of various ice creams
            private string[] Flavor;
            private string[] Container;
            private string[] Ingredient;
    
            // Additional factor used to process an ice scream order
            private int Scoops;
            private decimal TotalPrice;
    
            // Variables that will hold the user's choice
            // These are declared "globally" so they can be 
            // shared among methods
            int ChoiceFlavor;
            int ChoiceContainer;
            int ChoiceIngredient;
    
            // This default constructor is the best place for 
            // us to initialize the array
            public IceCream()
            {
                Flavor = new string[10];
                Flavor[0] = "Vanilla";
                Flavor[1] = "Cream of Cocoa";
                Flavor[2] = "Chocolate Chip";
                Flavor[3] = "Organic Strawberry";
                Flavor[4] = "Butter Pecan";
                Flavor[5] = "Cherry Coke";
                Flavor[6] = "Chocolate Brownies";
                Flavor[7] = "Caramel Au Lait";
                Flavor[8] = "Chunky Butter";
                Flavor[9] = "Chocolate Cookie";
    
                Ingredient = new string[4];
                Ingredient[0] = "No Ingredient";
                Ingredient[1] = "Peanuts";
                Ingredient[2] = "M & M";
                Ingredient[3] = "Cookies";
    
                Container = new string[3];
                Container[0] = "Cone";
                Container[1] = "Cup";
                Container[2] = "Bowl";
            }
    
            // This method requests a flavor from the user and
            // returns the choice
            public void ChooseFlavor()
            {
                // Make sure the user selects a valid number 
                //that represents a flavor...
                do
                {
                    // In case the user types a symbol that 
                    // is not a number
                    try
                    {
                        Console.WriteLine("What type of flavor do you want?");
                        for (int i = 0; i < Flavor.Length; i++)
                            Console.WriteLine("{0} - {1}", i + 1, Flavor[i]);
                        Console.Write("Your Choice? ");
                        ChoiceFlavor = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)	// display an appropriate message
                    {
                        Console.WriteLine("You must enter a valid number " +
                                          "and no other character!");
                    }
    
                    // If the user typed an invalid number out of the 
                    // allowed range
                    // let him or her know and provide another chance
                    if (ChoiceFlavor < 1 || ChoiceFlavor > Flavor.Length)
                        Console.WriteLine("Invalid Choice - Try Again!\n");
                } while (ChoiceFlavor < 1 || ChoiceFlavor > Flavor.Length);
            }
    
            // This method allows the user to select a container
            public void ChooseContainer()
            {
                // Make sure the user selects a valid number that 
                // represents a container
                do
                {
                    // If the user types a symbol that is not a number
                    try
                    {
                        Console.WriteLine("What type of container do you want?");
                        for (int i = 0; i < Container.Length; i++)
                            Console.WriteLine("{0} - {1}", i + 1, Container[i]);
                        Console.Write("Your Choice? ");
                        ChoiceContainer = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)	// display an appropriate message
                    {
                        Console.WriteLine("You must enter a valid " +
                                          "number and no other character!");
                    }
    
                    // If the user typed an invalid number out of the 
                    // allowed range
                    // let him or her know and provide another chance
                    if ((ChoiceContainer < 1) ||
                        (ChoiceContainer > Container.Length))
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while ((ChoiceContainer < 1) ||
                         (ChoiceContainer > Container.Length));
            }
    
            public void ChooseIngredient()
            {
                do
                {
                    try
                    {
                        Console.WriteLine("Do you want an ingredient or not");
                        for (int i = 0; i < Ingredient.Length; i++)
                            Console.WriteLine("{0} - {1}",
                                              i + 1,
                                              Ingredient[i]);
                        Console.Write("Your Choice? ");
                        ChoiceIngredient = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You must enter a valid " +
                                          "number and no other character!");
                    }
    
                    if ((ChoiceIngredient < 1) ||
                        (ChoiceIngredient > Ingredient.Length))
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while ((ChoiceIngredient < 1) ||
                         (ChoiceIngredient > Ingredient.Length));
            }
    
            public void SpecifyNumberOfScoops()
            {
                do
                {
                    try
                    {
                        Console.Write("How many scoops(1, 2, or 3)? ");
                        Scoops = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You must enter a valid number " +
                                          "and no other character!");
                    }
    
                    if (Scoops < 1 || Scoops > 3)
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while (Scoops < 1 || Scoops > 3);
            }
    
            // This method is used to process a customer order
            // It uses the values of the above methods
            public void ProcessAnOrder()
            {
                //			int ChoiceFlavor;
                //			int ChoiceContainer;
                //			int ChoiceIngredient;
                decimal PriceIngredient, PriceScoop;
    
                // Let the user know that this is a vending machine
                Console.WriteLine("=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
                Console.WriteLine("Ice Scream Vending Machine");
                Console.WriteLine("-----------------------------------");
    
                // Let the user select the components of the ice scream
                Request Get = new Request(ChooseFlavor);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(ChooseContainer);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(ChooseIngredient);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(SpecifyNumberOfScoops);
                Get();
                Console.WriteLine("-----------------------------------");
    
                // If the user selects an ingredient instead of "No Ingredient",
                // add $0.50 to the order
                if ((ChoiceIngredient == 2) ||
                    (ChoiceIngredient == 3) ||
                    (ChoiceIngredient == 4))
                    PriceIngredient = 0.50M;
                else
                    PriceIngredient = 0.00M;
    
                // Instead of multiplying a number scoops to a value,
                // We will use an incremental value depending on 
                // the number of scoops
                if (Scoops == 1)
                    PriceScoop = 0.65M;
                else if (Scoops == 2)
                    PriceScoop = 1.05M;
                else
                    PriceScoop = 1.55M;
    
                // Calculate the total price of the ice scream
                TotalPrice = BasePrice + PriceScoop + PriceIngredient;
    
                // Create the ice scream...
    
                // And display a receipt to the user
                DisplayReceipt();
            }
    
            // This method is used to display a receipt to the user
            public void DisplayReceipt()
            {
                Console.WriteLine("\n=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
                Console.WriteLine("Ice Scream Order");
                Console.WriteLine("-----------------------------------");
                Console.WriteLine("Flavor:      {0}",
                                  Flavor[ChoiceFlavor - 1]);
                Console.WriteLine("Container:   {0}",
                                  Container[ChoiceContainer - 1]);
                Console.WriteLine("Ingredient:  {0}",
                                  Ingredient[ChoiceIngredient - 1]);
                Console.WriteLine("Scoops:      {0}", Scoops);
                Console.WriteLine("Total Price: {0:C}", TotalPrice);
                Console.WriteLine("=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=\n");
            }
    
            public void SaveOrder()
            {
                string strNameOfFile;
    
                Console.Write("Please enter your initials or the name " +
                                  "we will use to remember your order: ");
                strNameOfFile = Console.ReadLine();
                strNameOfFile = strNameOfFile + ".icr";
    
                // Find out if the user entered a name of a file 
                // that is already in the machine
                if (File.Exists(strNameOfFile))
                {
                    char answer;
    
                    FileStream stmIceCream =
                        new FileStream(strNameOfFile, FileMode.Create);
                    BinaryWriter bnwIceCream =
                        new BinaryWriter(stmIceCream);
    
                    try
                    {
    
                        // If so, find out if the user wants to 
                        // replace the old file
                        Console.WriteLine("The file you entered exists already.");
                        Console.Write("Do you want to replace it(y/n)?");
                        answer = char.Parse(Console.ReadLine());
    
                        // If the customer wants to replace it...
                        if (answer == 'y' || answer == 'Y')
                        {
                            // ... do so
                            Console.WriteLine("The former order with the same " +
                                              "name will be replaced");
    
                            Console.WriteLine("\n=-= Ice Scream Vending Machine =-=");
                            Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                            bnwIceCream.Write(Flavor[ChoiceFlavor - 1]);
                            bnwIceCream.Write(Container[ChoiceContainer - 1]);
                            bnwIceCream.Write(Ingredient[ChoiceIngredient - 1]);
                            bnwIceCream.Write(Scoops);
                            bnwIceCream.Write(TotalPrice);
                        }
                        // If the customer wants to save the new order with 
                        // a different name
                        else if (answer == 'n' || answer == 'N')
                        {
                            // Ask the user to enter a name to remember the order
                            Console.Write("Please enter a name we will use " +
                                          "to remember this order: ");
                            strNameOfFile = Console.ReadLine();
                            strNameOfFile = strNameOfFile + ".icr";
    
                            stmIceCream =
    				new FileStream(strNameOfFile, FileMode.Create);
                            bnwIceCream = new BinaryWriter(stmIceCream);
    
                            Console.WriteLine("\n=-= Ice Scream Vending Machine =-=");
                            Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                            bnwIceCream.Write(Flavor[ChoiceFlavor - 1]);
                            bnwIceCream.Write(Container[ChoiceContainer - 1]);
                            bnwIceCream.Write(Ingredient[ChoiceIngredient - 1]);
                            bnwIceCream.Write(Scoops);
                            bnwIceCream.Write(TotalPrice);
                        }
                        else
                            Console.WriteLine("Invalid Answer - We will close");
                    }
                    finally
                    {
                        bnwIceCream.Close();
                        stmIceCream.Close();
                    }
                }
                else
                {
                    FileStream stmIceCream =
                        new FileStream(strNameOfFile, FileMode.Create);
                    BinaryWriter bnwIceCream =
                        new BinaryWriter(stmIceCream);
    
                    try
                    {
                        Console.WriteLine("\n=-= Ice Scream Vending Machine =-=");
                        Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                        bnwIceCream.Write(Flavor[ChoiceFlavor - 1]);
                        bnwIceCream.Write(Container[ChoiceContainer - 1]);
                        bnwIceCream.Write(Ingredient[ChoiceIngredient - 1]);
                        bnwIceCream.Write(Scoops);
                        bnwIceCream.Write(TotalPrice);
                    }
                    finally
                    {
                        bnwIceCream.Close();
                        stmIceCream.Close();
                    }
                }
            }
    
            public void OpenOrder()
            {
                string strNameOfFile;
    
                string SelectedFlavor;
                string SelectedContainer;
                string SelectedIngredient;
    
                // Ask the user to enter a name of a previously saved order
                Console.Write("Please enter the name you previously " +
                              "gave to remember your order: ");
                strNameOfFile = Console.ReadLine();
                strNameOfFile = strNameOfFile + ".icr";
    
                FileStream stmIceCream =
                    new FileStream(strNameOfFile, FileMode.Open);
                BinaryReader bnrIceCream =
                    new BinaryReader(stmIceCream);
    
                try
                {
                    // Find out if this order was previously saved in the machine
                    if (File.Exists(strNameOfFile))
                    {
                        // If so, open it
                        SelectedFlavor = bnrIceCream.ReadString();
                        SelectedContainer = bnrIceCream.ReadString();
                        SelectedIngredient = bnrIceCream.ReadString();
                        Scoops = bnrIceCream.ReadInt32();
                        TotalPrice = bnrIceCream.ReadDecimal();
    
                        // And display it to the user
                        Console.WriteLine("\n=-= Ice Scream Vending Machine =-=");
                        Console.WriteLine(" Previous Order: {0}", strNameOfFile);
                        Console.WriteLine("Flavor:      {0}", SelectedFlavor);
                        Console.WriteLine("Container:   {0}", SelectedContainer);
                        Console.WriteLine("Ingredient:  {0}", SelectedIngredient);
                        Console.WriteLine("Scoops:      {0}", Scoops);
                        Console.WriteLine("Total Price: {0:C}\n", TotalPrice);
                    }
                    else
                        Console.WriteLine("The name you entered is not " +
                                          "registered in our previous orders");
                }
                finally
                {
                    bnrIceCream.Close();
                    stmIceCream.Close();
                }
            }
        }
    }
     
    Accédez au fichier Program.cs et changez le comme suit :
     
    using System;
    
    namespace IceCream4
    {
        class Program
        {
            static int Main(string[] args)
            {
                char answer = 'n';
                IceCream ic = new IceCream();
                Request process = new Request(ic.ProcessAnOrder);
    
                Console.Write("Do you want to re-order a previously " +
                              "saved order(y/n)? ");
                answer = char.Parse(Console.ReadLine());
    
                if (answer == 'y' || answer == 'Y')
                    ic.OpenOrder();
                else
                {
                    process();
                    Console.Write("Do you want us to remember this " +
                                  "order the next time you come to " +
                                  "get your ice scream (y/n)? ");
                    answer = char.Parse(Console.ReadLine());
                    if (answer == 'y' || answer == 'Y')
                        ic.SaveOrder();
                    else
                        Console.WriteLine("\nIt was nice serving you." +
                                          "\nCome Again!!!\n");
                }
    
                return 0;
            }
        }
    }
  8. Exécutez l'application et l'examiner. Voici un exemple :
     
    Do you want to re-order a previously saved order(y/n)? n
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    Ice Scream Vending Machine
    -----------------------------------
    What type of flavor do you want?
    1 - Vanilla
    2 - Cream of Cocoa
    3 - Chocolate Chip
    4 - Organic Strawberry
    5 - Butter Pecan
    6 - Cherry Coke
    7 - Chocolate Brownies
    8 - Caramel Au Lait
    9 - Chunky Butter
    10 - Chocolate Cookie
    Your Choice? 6
    -----------------------------------
    What type of container do you want?
    1 - Cone
    2 - Cup
    3 - Bowl
    Your Choice? 2
    -----------------------------------
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? 1
    -----------------------------------
    How many scoops(1, 2, or 3)? 2
    -----------------------------------
    
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    Ice Scream Order
    -----------------------------------
    Flavor:      Cherry Coke
    Container:   Cup
    Ingredient:  No Ingredient
    Scoops:      2
    Total Price: $2.60
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    
    Do you want us to remember this order the next time you 
    come to get your ice scream (y/n)? n
    
    It was nice serving you.
    Come Again!!!
    
    Press any key to continue . . .
  9. Fermez la fenêtre DOS
  10. Exécutez l'application et l'examiner. Écrire un nom de fichier faux. Voici un exemple :
     
    Do you want to re-order a previously saved order(y/n)? y
    Please enter the name you previously gave to remember your order: dtr
    
    Unhandled Exception: System.IO.FileNotFoundException: Could not find file 'C:\Do
    cuments and Settings\Administrator\My Documents\Visual Studio 2005\Projects\Vend
    ingMachine4\IceCream4\bin\Release\dtr.icr'.
    File name: 'C:\Documents and Settings\Administrator\My Documents\Visual Studio 2
    005\Projects\VendingMachine4\IceCream4\bin\Release\dtr.icr'
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, I
    nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions o
    ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
       at System.IO.FileStream..ctor(String path, FileMode mode)
       at IceCream4.IceCream.OpenOrder() in C:\Documents and Settings\Administrator
    \My Documents\Visual Studio 2005\Projects\VendingMachine4\IceCream4\IceCream.cs
    :line 360
       at IceCream4.Program.Main(String[] args) in C:\Documents and Settings\Adminis
    trator\My Documents\Visual Studio 2005\Projects\VendingMachine4\IceCream4\Progra
    m.cs:line 18
    Press any key to continue . . .
  11. Fermez la fenêtre DOS

Manipulation d'exception du  .NET Framework pour le traitement de fichier

Dans la leçon précédente comme dans notre introduction au traitement de fichier, nous nous sommes comportés comme si tout était bien. Malheureusement, le traitement de fichier peut être très strict dans ses tâches. Basé sur ceci, .NET Framework fournit diverses classes d'Exceptions orientées pour traiter avec presque n'importe quel type d'exception à laquelle vous pouvez penser.

Un des aspects les plus importants du traitement de fichier est le nom du fichier qui sera traité. Dans certains cas vous pouvez fournir ce nom à l'application ou au document. Dans quelques autres cas, vous laisseriez l'utilisateur indiquer le nom du chemin. Indépendamment de la façon dont le nom du dossier serait fourni au logiciel d'exploitation, quand ce nom agi dessus, le compilateur est invité à travailler sur le fichier. Si le fichier n'existe pas, l'opération ne peut pas être exécutée. En outre, le compilateur rejetterait une erreur. Il y a beaucoup d'autres exceptions qui peuvent être rejetées en raison de quelque chose de mauvais survenue pendant le traitement de fichier :

FileNotFoundException : L'exception jetée quand un fichier n'a pas été trouvé est de type FileNotFoundException. Voici un exemple de manipulation :

using System;
using System.IO;

public class Program
{
    static int Main(string[] args)
    {
/*        string NameOfFile = "Members.clb";
	
        FileStream fstPersons = 
            new FileStream(NameOfFile, FileMode.Create);
        BinaryWriter wrtPersons = new BinaryWriter(fstPersons);
        
        try 
        {
            wrtPersons.Write("James Bloch");
            wrtPersons.Write("Catherina Wallace");
            wrtPersons.Write("Bruce Lamont");
            wrtPersons.Write("Douglas Truth");
        }
        finally
        {
            wrtPersons.Close();
            fstPersons.Close();
        }*/


        string NameOfFile = "Members.clc";
        string strLine = null;

        try
        {
            FileStream fstMembers =
                new FileStream(NameOfFile, FileMode.Open);
            BinaryReader rdrMembers = new BinaryReader(fstMembers);

            try
            {
                strLine = rdrMembers.ReadString();
                Console.WriteLine(strLine);
                strLine = rdrMembers.ReadString();
                Console.WriteLine(strLine);
                strLine = rdrMembers.ReadString();
                Console.WriteLine(strLine);
                strLine = rdrMembers.ReadString();
                Console.WriteLine(strLine);
            }
            finally
            {
                rdrMembers.Close();
                fstMembers.Close();
            }
        }
        catch (FileNotFoundException ex)
        {
            Console.Write("Error: " + ex.Message);
            Console.WriteLine(" May be the file doesn't exist " +
                              "or you typed it wrong!");
        }

        return 0;
    }
} 

Voici un exemple de ce que ceci produirait :

Error: Could not find file 'C:\Documents and Settings\Administrator\Local 
Settings\Application Data\Temporary 
Projects\ConsoleApplication1\bin\Release\Members.clc'. 
May be the file doesn't exist or you typed it wrong!
Press any key to continue . . .

IOException : Comme mentionné déjà, pendant le traitement de fichier, n'importe quoi a pu tourner mal. Si vous ne savez pas ce qui a causé une erreur, vous pouvez rejeter l'exception IOException.

Étude pratiqueÉtude pratique : Manipulation des exceptions de traitement de fichier

  1. Pour ejeter des exceptions, changez les méthodes de traitement de fichier à partir du fichier IceScream.cs comme suit :
     
    using System;
    using System.IO;
    
    namespace IceCream4
    {
        delegate void Request();
    
        // This class is used to create and manage an ice scream
        // and to process an order
        public sealed class IceCream
        {
            // This is the base price of an ice scream
            // Optional values may be added to it
            public const decimal BasePrice = 1.55M;
    
            // These arrays are used to build the components 
            // of various ice screams
            // In C#, we can allocate an array's memory in 
            // the body of the class
            private string[] Flavor;
            private string[] Container;
            private string[] Ingredient;
    
            // Additional factor used to process an ice scream order
            private int Scoops;
            private decimal TotalPrice;
    
            // Variables that will hold the user's choice
            // These are declared "globally" so they can be 
            // shared among methods
            int ChoiceFlavor;
            int ChoiceContainer;
            int ChoiceIngredient;
    
            // This default constructor is the best place for 
            // us to initialize the array
            public IceCream()
            {
                Flavor = new string[10];
                Flavor[0] = "Vanilla";
                Flavor[1] = "Cream of Cocoa";
                Flavor[2] = "Chocolate Chip";
                Flavor[3] = "Organic Strawberry";
                Flavor[4] = "Butter Pecan";
                Flavor[5] = "Cherry Coke";
                Flavor[6] = "Chocolate Brownies";
                Flavor[7] = "Caramel Au Lait";
                Flavor[8] = "Chunky Butter";
                Flavor[9] = "Chocolate Cookie";
    
                Ingredient = new string[4];
                Ingredient[0] = "No Ingredient";
                Ingredient[1] = "Peanuts";
                Ingredient[2] = "M & M";
                Ingredient[3] = "Cookies";
    
                Container = new string[3];
                Container[0] = "Cone";
                Container[1] = "Cup";
                Container[2] = "Bowl";
            }
    
            // This method requests a flavor from the user and
            // returns the choice
            public void ChooseFlavor()
            {
                // Make sure the user selects a valid number 
                //that represents a flavor...
                do
                {
                    // In case the user types a symbol that 
                    // is not a number
                    try
                    {
                        Console.WriteLine("What type of flavor do you want?");
                        for (int i = 0; i < Flavor.Length; i++)
                            Console.WriteLine("{0} - {1}", i + 1, Flavor[i]);
                        Console.Write("Your Choice? ");
                        ChoiceFlavor = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)	// display an appropriate message
                    {
                        Console.WriteLine("You must enter a valid number " +
                                          "and no other character!");
                    }
    
                    // If the user typed an invalid number out of the 
                    // allowed range
                    // let him or her know and provide another chance
                    if (ChoiceFlavor < 1 || ChoiceFlavor > Flavor.Length)
                        Console.WriteLine("Invalid Choice - Try Again!\n");
                } while (ChoiceFlavor < 1 || ChoiceFlavor > Flavor.Length);
            }
    
            // This method allows the user to select a container
            public void ChooseContainer()
            {
                // Make sure the user selects a valid number that 
                // represents a container
                do
                {
                    // If the user types a symbol that is not a number
                    try
                    {
                        Console.WriteLine("What type of container do you want?");
                        for (int i = 0; i < Container.Length; i++)
                            Console.WriteLine("{0} - {1}", i + 1, Container[i]);
                        Console.Write("Your Choice? ");
                        ChoiceContainer = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)	// display an appropriate message
                    {
                        Console.WriteLine("You must enter a valid " +
                                          "number and no other character!");
                    }
    
                    // If the user typed an invalid number out of the 
                    // allowed range
                    // let him or her know and provide another chance
                    if ((ChoiceContainer < 1) ||
                        (ChoiceContainer > Container.Length))
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while ((ChoiceContainer < 1) ||
                         (ChoiceContainer > Container.Length));
            }
    
            public void ChooseIngredient()
            {
                do
                {
                    try
                    {
                        Console.WriteLine("Do you want an ingredient or not");
                        for (int i = 0; i < Ingredient.Length; i++)
                            Console.WriteLine("{0} - {1}",
                                              i + 1,
                                              Ingredient[i]);
                        Console.Write("Your Choice? ");
                        ChoiceIngredient = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You must enter a valid " +
                                          "number and no other character!");
                    }
    
                    if ((ChoiceIngredient < 1) ||
                        (ChoiceIngredient > Ingredient.Length))
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while ((ChoiceIngredient < 1) ||
                         (ChoiceIngredient > Ingredient.Length));
            }
    
            public void SpecifyNumberOfScoops()
            {
                do
                {
                    try
                    {
                        Console.Write("How many scoops(1, 2, or 3)? ");
                        Scoops = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You must enter a valid number " +
                                          "and no other character!");
                    }
    
                    if (Scoops < 1 || Scoops > 3)
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while (Scoops < 1 || Scoops > 3);
            }
    
            // This method is used to process a customer order
            // It uses the values of the above methods
            public void ProcessAnOrder()
            {
                //			int ChoiceFlavor;
                //			int ChoiceContainer;
                //			int ChoiceIngredient;
                decimal PriceIngredient, PriceScoop;
    
                // Let the user know that this is a vending machine
                Console.WriteLine("=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
                Console.WriteLine("Ice Scream Vending Machine");
                Console.WriteLine("-----------------------------------");
    
                // Let the user select the components of the ice scream
                Request Get = new Request(ChooseFlavor);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(ChooseContainer);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(ChooseIngredient);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(SpecifyNumberOfScoops);
                Get();
                Console.WriteLine("-----------------------------------");
    
                // If the user selects an ingredient instead of "No Ingredient",
                // add $0.50 to the order
                if ((ChoiceIngredient == 2) ||
                    (ChoiceIngredient == 3) ||
                    (ChoiceIngredient == 4))
                    PriceIngredient = 0.50M;
                else
                    PriceIngredient = 0.00M;
    
                // Instead of multiplying a number scoops to a value,
                // We will use an incremental value depending on 
                // the number of scoops
                if (Scoops == 1)
                    PriceScoop = 0.65M;
                else if (Scoops == 2)
                    PriceScoop = 1.05M;
                else
                    PriceScoop = 1.55M;
    
                // Calculate the total price of the ice scream
                TotalPrice = BasePrice + PriceScoop + PriceIngredient;
    
                // Create the ice scream...
    
                // And display a receipt to the user
                DisplayReceipt();
            }
    
            // This method is used to display a receipt to the user
            public void DisplayReceipt()
            {
                Console.WriteLine("\n=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
                Console.WriteLine("Ice Scream Order");
                Console.WriteLine("-----------------------------------");
                Console.WriteLine("Flavor:      {0}",
                                  Flavor[ChoiceFlavor - 1]);
                Console.WriteLine("Container:   {0}",
                                  Container[ChoiceContainer - 1]);
                Console.WriteLine("Ingredient:  {0}",
                                  Ingredient[ChoiceIngredient - 1]);
                Console.WriteLine("Scoops:      {0}", Scoops);
                Console.WriteLine("Total Price: {0:C}", TotalPrice);
                Console.WriteLine("=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=\n");
            }
    
            public void SaveOrder()
            {
                string strNameOfFile;
    
                Console.Write("Please enter your initials or the name " +
                                  "we will use to remember your order: ");
                strNameOfFile = Console.ReadLine();
                strNameOfFile = strNameOfFile + ".icr";
    
                try
                {
                    // Find out if the user entered a name of a file 
                    // that is already in the machine
                    if (File.Exists(strNameOfFile))
                    {
                        char answer;
    
                        FileStream stmIceCream =
                            new FileStream(strNameOfFile, FileMode.Create);
                        BinaryWriter bnwIceCream =
                            new BinaryWriter(stmIceCream);
    
                        try
                        {
    
                            // If so, find out if the user wants to 
                            // replace the old file
                            Console.WriteLine("The file you entered exists already.");
                            Console.Write("Do you want to replace it(y/n)?");
                            answer = char.Parse(Console.ReadLine());
    
                            // If the customer wants to replace it...
                            if (answer == 'y' || answer == 'Y')
                            {
                                // ... do so
                                Console.WriteLine("The former order with the same " +
                                                  "name will be replaced");
    
                                Console.WriteLine("\n=-= Ice Scream " +
    						"Vending Machine =-=");
                                Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                                bnwIceCream.Write(Flavor[ChoiceFlavor - 1]);
                                bnwIceCream.Write(Container[ChoiceContainer - 1]);
                                bnwIceCream.Write(Ingredient[ChoiceIngredient - 1]);
                                bnwIceCream.Write(Scoops);
                                bnwIceCream.Write(TotalPrice);
                            }
                            // If the customer wants to save the new order with 
                            // a different name
                            else if (answer == 'n' || answer == 'N')
                            {
                                // Ask the user to enter a name to remember the order
                                Console.Write("Please enter a name we will use " +
                                              "to remember this order: ");
                                strNameOfFile = Console.ReadLine();
                                strNameOfFile = strNameOfFile + ".icr";
    
                                try
                                {
                                    stmIceCream = new FileStream(strNameOfFile,
    							 FileMode.Create);
                                    bnwIceCream = new BinaryWriter(stmIceCream);
    
                                    Console.WriteLine("\n=-= Ice Scream " +
    						  "Vending Machine =-=");
                                    Console.WriteLine(" Saving Order: {0}",
    						 strNameOfFile);
                                    bnwIceCream.Write(Flavor[ChoiceFlavor - 1]);
                                bnwIceCream.Write(Container[ChoiceContainer - 1]);
                                bnwIceCream.Write(Ingredient[ChoiceIngredient - 1]);
                                    bnwIceCream.Write(Scoops);
                                    bnwIceCream.Write(TotalPrice);
                                }
                                catch (IOException)
                                {
                                    Console.Write("\nThe file you wanted us to " +
    						"create exists already. ");
                                    Console.WriteLine("In case it was registered " +
    						  "by a different customer, " +
    						  "we will not delete it.");
                                }
                            }
                            else
                                Console.WriteLine("Invalid Answer - We will close");
                        }
                        catch (IOException)
                        {
                            Console.Write("\nThat file exists already. ");
                            Console.WriteLine("We need to preserve it just in " +
    					"case another customer will require it.");
                        }
                        finally
                        {
                            bnwIceCream.Close();
                            stmIceCream.Close();
                        }
                    }
                    else
                    {
                        FileStream stmIceCream =
                            new FileStream(strNameOfFile, FileMode.Create);
                        BinaryWriter bnwIceCream =
                            new BinaryWriter(stmIceCream);
    
                        try
                        {
                            Console.WriteLine("\n=-= Ice Scream Vending Machine =-=");
                            Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                            bnwIceCream.Write(Flavor[ChoiceFlavor - 1]);
                            bnwIceCream.Write(Container[ChoiceContainer - 1]);
                            bnwIceCream.Write(Ingredient[ChoiceIngredient - 1]);
                            bnwIceCream.Write(Scoops);
                            bnwIceCream.Write(TotalPrice);
                        }
                        finally
                        {
                            bnwIceCream.Close();
                            stmIceCream.Close();
                        }
                    }
                }
                catch (IOException ex)
                {
                    Console.WriteLine("\nError: " + ex.Message);
                    Console.WriteLine("Operation Canceled: The file you want " +
    					"to create exists already.");
                }
            }
    
            public void OpenOrder()
            {
                string strNameOfFile;
    
                string SelectedFlavor;
                string SelectedContainer;
                string SelectedIngredient;
    
                // Ask the user to enter a name of a previously saved order
                Console.Write("Please enter the name you previously " +
                              "gave to remember your order: ");
                strNameOfFile = Console.ReadLine();
                strNameOfFile = strNameOfFile + ".icr";
    
                try
                {
                    FileStream stmIceCream =
                        new FileStream(strNameOfFile, FileMode.Open);
                    BinaryReader bnrIceCream =
                        new BinaryReader(stmIceCream);
    
                    try
                    {
                        // Find out if this order was previously saved in the machine
                        if (File.Exists(strNameOfFile))
                        {
                            // If so, open it
                            SelectedFlavor = bnrIceCream.ReadString();
                            SelectedContainer = bnrIceCream.ReadString();
                            SelectedIngredient = bnrIceCream.ReadString();
                            Scoops = bnrIceCream.ReadInt32();
                            TotalPrice = bnrIceCream.ReadDecimal();
    
                            // And display it to the user
                            Console.WriteLine("\n=-= Ice Scream Vending Machine =-=");
                            Console.WriteLine(" Previous Order: {0}", strNameOfFile);
                            Console.WriteLine("Flavor:      {0}", SelectedFlavor);
                            Console.WriteLine("Container:   {0}", SelectedContainer);
                            Console.WriteLine("Ingredient:  {0}", SelectedIngredient);
                            Console.WriteLine("Scoops:      {0}", Scoops);
                            Console.WriteLine("Total Price: {0:C}\n", TotalPrice);
                        }
                        else
                            Console.WriteLine("The name you entered is not " +
                                              "registered in our previous orders");
                    }
                    finally
                    {
                        bnrIceCream.Close();
                        stmIceCream.Close();
                    }
                }
                catch (FileNotFoundException ex)
                {
                    Console.Write("\nError: " + ex.Message);
                    Console.WriteLine("It is unlikely that the file exists in " +
    				  "our machine's register.");
                }
            }
        }
    }
  2. Exécutez l'application et l'examiner
  3. Fermez la fenêtre DOS
  

Précédent Copyright © 2007-2008, Yevol Suivant