Home

Exception Handling in File Processing

 

Finally

To handle exceptions, you can use the try, catch, and throw keywords. These allowed us to perform normal assignments in a try section and then handle an exception, if any, in a catch block. We also mentioned that, when you create a stream, the operating system must allocate resources and dedicate them to the file processing operations. Additional resources may be provided for the object that is in charge of writing to, or reading from, the stream. We also saw that, when the streaming was over, we should free the resources and give them back to the operating system. To do this, we called the Close() method of the variable that was using resources.

More than any other assignment, file processing is in prime need of exception handling. During file processing, there are many things that can go wrong. For this reason, the creation and/or management of streams should be performed in a try block to get ready to handle exceptions that would occur. Besides actually handling exceptions, the C# language provides a special keyword used free resources. This keyword is finally.

The finally keyword is used to create a section of an exception. Like catch, a finally block cannot exist by itself. It can be created following a try section. The formula used would be:

try
{
}
finally
{
}

Based on this, the finally section has a body of its own, delimited by its curly brackets. Like catch, the finally section is created after the try section. Unlike catch, finally never has parentheses and never takes arguments. Unlike catch, the finally section is always executed. Because the finally clause always gets executed, you can include any type of code in it but it is usually appropriate to free the resources that were allocated previously. In the same way, you can use a finally section to free resources used when reading from a stream. Here are examples:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FileProcessing1
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string Filename = "Employees.spr";
            
            FileStream fstPersons = new FileStream(Filename,
                FileMode.Create);
            BinaryWriter wrtPersons = new BinaryWriter(fstPersons);

            try
            {
                wrtPersons.Write(txtPerson1.Text);
                wrtPersons.Write(txtPerson2.Text);
                wrtPersons.Write(txtPerson3.Text);
                wrtPersons.Write(txtPerson4.Text);

                txtPerson1.Text = "";
                txtPerson2.Text = "";
                txtPerson3.Text = "";
                txtPerson4.Text = "";
            }
            finally
            {
                wrtPersons.Close();
                fstPersons.Close();
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            string Filename = "Employees.spr";
            FileStream fstPersons = new FileStream(Filename, FileMode.Open);
            BinaryReader rdrPersons = new BinaryReader(fstPersons);

            try
            {
                txtPerson1.Text = rdrPersons.ReadString();
                txtPerson2.Text = rdrPersons.ReadString();
                txtPerson3.Text = rdrPersons.ReadString();
                txtPerson4.Text = rdrPersons.ReadString();
            }
            finally
            {
                rdrPersons.Close();
                fstPersons.Close();
            }
        }
    }
}

Of course, since the whole block of code starts with a try section, it is used for exception handling. This means that you can add the necessary and appropriate catch section(s) (but you don't have to).

Practical LearningPractical Learning: Finally Releasing Resources

  1. Right-click the form and click View Code
  2. Change the following two events :
     
    private void btnClose_Click(object sender, EventArgs e)
    {
        System.Windows.Forms.DialogResult answer =
         	MessageBox.Show(
    		"Do you want to save this order to remember it " +
                             "the next time you come to " +
                             "get your ice scream?",
                 "Ice Cream Vending Machine",
                 MessageBoxButtons.YesNo,
                 MessageBoxIcon.Question);
    
        if (answer == System.Windows.Forms.DialogResult.Yes)
        {
            string Filename =
                        Microsoft.VisualBasic.Interaction.InputBox(
                        "Please type your initials and press Enter",
                        "Ice Cream Vending Machine", "AA", 100, 100);
            if (Filename != "")
            {
                Filename = Filename + ".icr";
    
                FileStream stmIceCream =
                           new FileStream(Filename, FileMode.Create);
                BinaryWriter bnwIceCream =
                                       new BinaryWriter(stmIceCream);
    
                try
                {
                    bnwIceCream.Write(dtpOrderDate.Value.ToShortDateString());
                    bnwIceCream.Write(dtpOrderTime.Value.ToShortTimeString());
                    bnwIceCream.Write(cboFlavors.Text);
                    bnwIceCream.Write(cboContainers.Text);
                    bnwIceCream.Write(cboIngredients.Text);
                    bnwIceCream.Write(txtScoops.Text);
                    bnwIceCream.Write(txtOrderTotal.Text);
                }
                finally
                {
                    bnwIceCream.Close();
                    stmIceCream.Close();
                }
    
                MessageBox.Show("The order has been saved");
            }
            else
                MessageBox.Show("The ice cream order will not be saved");
        }
    
        MessageBox.Show("Good Bye: It was a delight serving you");
        Close();
    }
    
    private void Form1_Load(object sender, EventArgs e)
    {
        string Filename =
                        Microsoft.VisualBasic.Interaction.InputBox(
                        "If you had previously ordered an ice cream here " +
                        "and you want to order the same, please type your " +
                        "initials and press Enter (otherwise, press Esc)",
                        "Ice Cream Vending Machine", "", 100, 100);
        if(Filename != "")
        {
                    Filename = Filename + ".icr";
    
                    string OrderDate;
                    string OrderTime;
                    string SelectedFlavor;
                    string SelectedContainer;
                    string SelectedIngredient;
                    string Scoops;
                    string OrderTotal;
    
                    FileStream stmIceCream =
                            new FileStream(Filename, FileMode.Open);
                    BinaryReader bnrIceCream =
                            new BinaryReader(stmIceCream);
    
                  // Find out if this order was previously saved in the machine
                    if (File.Exists(Filename))
                    {
                        // If so, open it
                        try
                        {
                            OrderDate = bnrIceCream.ReadString();
                            OrderTime = bnrIceCream.ReadString();
                            SelectedFlavor = bnrIceCream.ReadString();
                            SelectedContainer = bnrIceCream.ReadString();
                            SelectedIngredient = bnrIceCream.ReadString();
                            Scoops = bnrIceCream.ReadString();
                            OrderTotal = bnrIceCream.ReadString();
    
                            // And display it to the user
                            dtpOrderDate.Value = DateTime.Parse(OrderDate);
                            dtpOrderTime.Value = DateTime.Parse(OrderTime);
                            cboFlavors.Text = SelectedFlavor;
                            cboContainers.Text = SelectedContainer;
                            cboIngredients.Text = SelectedIngredient;
                            txtScoops.Text = Scoops.ToString();
                            txtOrderTotal.Text = OrderTotal;
                        }
                        finally
                        {
                            bnrIceCream.Close();
                            stmIceCream.Close();
                        }
                    }
                    else
                      MessageBox.Show("It looks like you have not previously " +
                                        "ordered an ice cream here");
        }
    }
  3. Execute the application and test it
  4. Close the form

.NET Framework Exception Handling for File Processing

In the previous lesson as our introduction to file processing, we behaved as if everything was alright. Unfortunately, file processing can be very strict in its assignments. Based on this, the .NET Framework provides various Exception-oriented classes to deal with almost any type of exception you can think of.

One of the most important aspects of file processing is the name of the file that will be dealt with. In some cases you can provide this name to the application or document. In some other cases, you would let the user specify the name of the path. Regardless of how the name of the file would be provided to the operating system, when this name is acted upon, the compiler is asked to work on the file. If the file doesn't exist, the operation cannot be carried. Furthermore, the compiler would throw an error. Here is an example:

private void btnOpen_Click(object sender, EventArgs e)
{
    string Filename = "contractors.spr";
    FileStream fstPersons = null;
    BinaryReader rdrPersons = null;

    fstPersons = new FileStream(Filename, FileMode.Open);
    rdrPersons = new BinaryReader(fstPersons);

    try
    {
        txtPerson1.Text = rdrPersons.ReadString();
        txtPerson2.Text = rdrPersons.ReadString();
        txtPerson3.Text = rdrPersons.ReadString();
        txtPerson4.Text = rdrPersons.ReadString();
    }
    finally
    {
        rdrPersons.Close();
        fstPersons.Close();
    }
}

Here is an example of an error that this would produce:

There are many other exceptions that can thrown as a result of something going bad during file processing:

FileNotFoundException: This exception is thrown when a file has not been found. Here is an example of handling it:

private void btnOpen_Click(object sender, EventArgs e)
{
    string Filename = "contractors.spr";

    try
    {
        FileStream fstPersons = new FileStream(Filename, FileMode.Open);
        BinaryReader rdrPersons = new BinaryReader(fstPersons);

        try
        {
            txtPerson1.Text = rdrPersons.ReadString();
            txtPerson2.Text = rdrPersons.ReadString();
            txtPerson3.Text = rdrPersons.ReadString();
            txtPerson4.Text = rdrPersons.ReadString();
        }
        finally
        {
            rdrPersons.Close();
            fstPersons.Close();
        }
    }
    catch(FileNotFoundException ex)
    {
        Console.Write("Error: " + ex.Message);
        MessageBox.Show(" May be the file doesn't exist or you typed it wrong!");
    }
}

Here is an example of what this would produce:

IOException: As mentioned already, during file processing, anything could go wrong. If you don't know what caused an error, you can throw the IOException exception.

Practical LearningPractical Learning: Handling File Processing Exceptions

  1. In the Types combo box, select IceCream1.Form1 and, in the Members combo box, select Form1_Load
  2. To handle a FileNotFoundException exception, change the event as follows:
     
    private void Form1_Load(object sender, EventArgs e)
    {
        string Filename = Microsoft.VisualBasic.Interaction.InputBox(
                          "If you had previously ordered an ice cream here " +
                          "and you want to order the same, please type your " +
                          "initials and press Enter (otherwise, press Esc)",
                          "Ice Cream Vending Machine", "", 100, 100);
        if (Filename != "")
        {
            Filename = Filename + ".icr";
    
            string OrderDate;
            string OrderTime;
            string SelectedFlavor;
            string SelectedContainer;
            string SelectedIngredient;
            string Scoops;
            string OrderTotal;
    
            try
            {
                FileStream stmIceCream =
                                new FileStream(Filename, FileMode.Open);
                BinaryReader bnrIceCream =
                                new BinaryReader(stmIceCream);
    
                // Find out if this order was previously saved in the machine
                if(File.Exists(Filename))
                {
                    // If so, open it
                    try
                    {
                        OrderDate = bnrIceCream.ReadString();
                        OrderTime = bnrIceCream.ReadString();
                        SelectedFlavor = bnrIceCream.ReadString();
                        SelectedContainer = bnrIceCream.ReadString();
                        SelectedIngredient = bnrIceCream.ReadString();
                        Scoops = bnrIceCream.ReadString();
                        OrderTotal = bnrIceCream.ReadString();
    
                        // And display it to the user
                        dtpOrderDate.Value = DateTime.Parse(OrderDate);
                        dtpOrderTime.Value = DateTime.Parse(OrderTime);
                        cboFlavors.Text = SelectedFlavor;
                        cboContainers.Text = SelectedContainer;
                        cboIngredients.Text = SelectedIngredient;
                        txtScoops.Text = Scoops.ToString();
                        txtOrderTotal.Text = OrderTotal;
                    }
                    finally
                    {
                        bnrIceCream.Close();
                        stmIceCream.Close();
                    }
                }
                else
                    MessageBox.Show("It looks like you have not previously " +
                                    "ordered an ice cream here");
            }
            catch (FileNotFoundException)
            {
                MessageBox.Show("There is no previous order with those initials");
            }
        }
    }
  3. Exercise the application and test it
  4. Close the form
 

Previous Copyright © 2007 FunctionX, Inc. Home