Home

Details on File Processing

 

Exception Handling in File Processing

 

Finally

So far, to handle exceptions, we were using 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, you can use the finally keyword to free resources.

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 such as those used during streaming. Here is an example:

System::Void btnSave_Click(System::Object^  sender, System::EventArgs^  e)
{
    String ^ NameOfFile = L"Persons.spr";

    FileStream ^ fstPersons = gcnew FileStream(NameOfFile,
					       FileMode::Create);
    BinaryWriter ^ wrtPersons = gcnew BinaryWriter(fstPersons);

    try {
        wrtPersons->Write(txtPerson1->Text);
        wrtPersons->Write(txtPerson2->Text);
        wrtPersons->Write(txtPerson3->Text);
        wrtPersons->Write(txtPerson4->Text);
    }
    finally
    {
        wrtPersons->Close();
        fstPersons->Close();
    }

    txtPerson1->Text = L"";
    txtPerson2->Text = L"";
    txtPerson3->Text = L"";
    txtPerson4->Text = L"";
}

In the same way, you can use a finally section to free resources used when reading from a stream. 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. Start Microsoft Visual C++/CLI or Visual Studio and create a Windows Forms Application named IceCream2
  2. In the Properties window, change the form's Text to Ice Cream Vending Machine
  3. In the Common Controls section of the Toolbox, click ToolTip and click the form
  4. In the Menu and Toolbars section of the Toolbox, click StatusStrip and click the form
  5. Design the form as follows:
     
    Control Name Text ToolTip on toolTip1 Additional Properties
    GroupBox        
    Label   Please enter your initials and click Open:    
    TextTox txtInitials   First enter your initials. Then click Open  
    Button btnFileProcessing Open First enter your initials. Then click Open  
    Label   Order Date:    
    DateTimePicker dtpOrderDate   Click the arrow to select a date Format: Short
    Label   Order Time:    
    DateTimePicker dtpOrderTime   Click each section, then click one of the arrows to change its value Format: Time
    ShowUpDown: True
    Label   Flavor:    
    ComboBox cboFlavors   Click the arrow to display a list, then select a flavor from the list DropDownStyle: DropDownList
    Label   Container:    
    ComboBox cboContainers   Click to display the list of containers and select one DropDownStyle: DropDownList
    Label   Ingredient:    
    ComboBox cboIngredients   Display the list of ingredients and make the customer's choice DropDownStyle: DropDownList
    Label   Scoops:    
    TextBox txtScoops 1 Enter the number of scoops (1, 2, or 3) to fill the container TextAlign: Right
    Label   Order Total:    
    TextBox txtOrderTotal 0.00 This displays the total amount of this order TextAlign: Right
    Label   Amount Tended:    
    TextBox txtAmountTended   Amount you inserted into the machine  
    Label   Change    
    TextBox txtChange   Amount given back to you  
    Button btnClose Close Click to end  
  6. Click the combo box to the right of the Flavor label. Then, in the Properties, click the ellipsis button Ellipsis of Items property and create the list with:
     
    Vanilla
    Cream of Cocoa
    Chocolate Chip
    Cherry Coke
    Butter Pecan
    Chocolate Cookie
    Chunky Butter
    Organic Strawberry
    Chocolate Brownies
    Caramel Au Lait
  7. Click OK
  8. Click the combo box to the right of the Container label. Then, in the Properties, click the ellipsis button Ellipsis of Items property and create the list with:
     
    Cone
    Cup
    Bowl
  9. Click OK
  10. Click the combo box to the right of the Ingredient label. Then, in the Properties, click the ellipsis button Ellipsis of Items property and create the list with:
     
    None
    Peanuts
    Mixed Nuts
    M & M
    Cookies
  11. Click OK
  12. To add a new form to the project, on the main menu, click Project -> Add Class...
  13. In the Templates section, click Windows Form and set the Name to FileProcessing
  14. Click Add and design the form as follows:
     
    Control Name Text Other Properties
    Label lblMessage Message: Modifiers: Public
    TextBox txtInitials   Modifiers: Public
    Button btnFileProcessing Process DialogResult: OK
    Modifiers: Public
  15. Return to the first form
  16. Double-click outside of any control, such as to the left side of the group box to generate the Load event of the form
  17. Implement the form's Load event as follows:
     
    System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)
    {
        Initials = L"";
        FileStream ^ stmIceCream = nullptr;
        BinaryReader ^ bnrIceCream = nullptr;
        FileProcessing ^ frmFileProcessing = gcnew FileProcessing;
    
        frmFileProcessing->lblMessage->Text = L"Enter your initials and click Open";
        frmFileProcessing->btnFileProcessing->Text = L"Open";
        frmFileProcessing->txtInitials->Text = L"";
        frmFileProcessing->txtInitials->Focus();
    
        if( frmFileProcessing->ShowDialog() == 
    		System::Windows::Forms::DialogResult::OK )
        {
    	Initials = frmFileProcessing->txtInitials->Text;
    	String ^ NameOfFile = frmFileProcessing->txtInitials->Text + L".icr";
    				 
    	String ^ OrderDate;
    	String ^ OrderTime;
    	String ^ SelectedFlavor;
    	String ^ SelectedContainer;
    	String ^ SelectedIngredient;
    	int Scoops;
    	double OrderTotal;
    
    	stmIceCream = gcnew FileStream(NameOfFile, FileMode::Open);
    	bnrIceCream = gcnew BinaryReader(stmIceCream);
    
    	try {
    	    OrderDate = bnrIceCream->ReadString();
    	    OrderTime = bnrIceCream->ReadString();
    	    SelectedFlavor = bnrIceCream->ReadString();
    	    SelectedContainer = bnrIceCream->ReadString();
    	    SelectedIngredient = bnrIceCream->ReadString();
    	    Scoops = bnrIceCream->ReadInt32();
    	    OrderTotal = bnrIceCream->ReadDouble();
    
    	    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.ToString(L"F");
    	}
    	finally
    	{
    	    bnrIceCream->Close();
    	    stmIceCream->Close();
    	}
        }
    }
  18. Execute the application and test it.
  19. On the form, click the Scoops text box and click the Events button Events of the Properties window 
  20. In the Events section of the Properties window, look for and double-click Leave to generate its event
  21. Implement it as follows:
     
    System::Void txtScoops_Leave(System::Object^  sender, System::EventArgs^  e)
    {
        double PriceContainer  = 0.00,
               PriceIngredient = 0.00,
               PriceScoops     = 0.00,
    	   OrderTotal      = 0.00;
        int NumberOfScoops     = 1;
    
        // The price of a container depends on which one the customer selected
        if( cboContainers->Text == L"Cone" )
    		PriceContainer = 0.55;
        else if( cboContainers->Text == L"Cup" )
    		PriceContainer = 0.75;
        else
    		PriceContainer = 1.15;
            
        // Find out if the customer wants any ingredient at all
        if( this->cboIngredients->Text == L"None" )
    		PriceIngredient = 0.00;
    	else
    		PriceIngredient = 0.95;
            
        try {
    	// Get the number of scoops
    	NumberOfScoops = int::Parse(this->txtScoops->Text);
    	
    	if( NumberOfScoops == 1 )
    		PriceScoops = 1.85;
    	else if( NumberOfScoops == 2 )
    		PriceScoops = 2.55;
    	else // if( NumberOfScoops == 3 )
    		PriceScoops = 3.25;
            
            // Make sure the user selected a flavor, 
            // otherwise, there is no reason to process an order
            if( this->cboFlavors->Text != L"" )
    	{
    	    OrderTotal = PriceScoops + PriceContainer + PriceIngredient;
    	    this->txtOrderTotal->Text = OrderTotal.ToString("F");
    	    txtAmountEntered->Text = OrderTotal.ToString("F");
    
    	    txtAmountEntered->Focus();
    
    	    System::Windows::FormsDialogResult answer = 
    			MessageBox::Show(
    			    L"Do you want to save this order to remember it "
                                L"the next time you come to "
                                L"get your Ice Cream?",
    			    L"Ice Cream Vending Machine",
    			    MessageBoxButtons::YesNo,
    			    MessageBoxIcon::Question);
    
    	    if( answer == System::Windows::Forms::DialogResult::Yes )
    	    {
    		MessageBox::Show(
    				L"Please enter your initials and click Save");
    		btnFileProcessing->Text = L"Save";
    		txtInitials->Text = L"";
    		txtInitials->Focus();
    	    }
    	}
        }
        catch(FormatException ^)
        {
    	MessageBox::Show(L"The value you entered for the scoops is not valid"
    	              L"\nOnly natural numbers such as 1, 2, or 3 are allowed"
    	                 L"\nPlease try again");
        }
    }
  22. Return to the form
  23. On the form, click the Amount Entered text box and, in the Events section of the Properties window, generate the Leave event
  24. Implement it as follows:
     
    System::Void txtAmountEntered_Leave(System::Object^  sender,
    		 System::EventArgs^  e)
    {
        double TotalOrder,
        AmountEntered = 0.00,
        Change;
    
        // Get the value of the total order. Actually, this value 
        // will be provided by the main form
        TotalOrder = double::Parse(this->txtOrderTotal->Text);
    	
        try 
        {
    	// The amount tended will be entered by the user
    	AmountEntered = double::Parse(this->txtAmountEntered->Text);
        }
        catch(FormatException ^)
        {
    	MessageBox::Show(L"The amount you entered is not "
    			 L"valid - Please try again!");
        }
    
        // Calculate the difference of both values, assuming 
        // that the amount tended is higher
        Change = AmountEntered - TotalOrder;
    
        // Display the result in the Difference text box
        this->txtChange->Text = Change.ToString("F");
    }
  25. Scroll up in the file and type the following:
     
    #pragma once
    
    #include "FileProcessing.h"
    
    namespace IceCream2 {
    
    	using namespace System;
    	using namespace System::ComponentModel;
    	using namespace System::Collections;
    	using namespace System::Windows::Forms;
    	using namespace System::Data;
    	using namespace System::Drawing;
    	using namespace System::IO;
    
    	/// <summary>
    	/// Summary for Form1
    	///
    	/// WARNING: If you change the name of this class, you will need to change the
    	///          'Resource File Name' property for the managed resource compiler tool
    	///          associated with all .resx files this class depends on.  Otherwise,
    	///          the designers will not be able to interact properly with localized
    	///          resources associated with this form.
    	/// </summary>
    	public ref class Form1 : public System::Windows::Forms::Form
    	{
    
    	. . . No Change
    
    	private: System::ComponentModel::IContainer^  components;
    			 String ^ Initials;
    
    	private:
    		/// <summary>
    		/// Required designer variable.
    		/// </summary>
    
    	}
    };
    }
  26. Return to the form
  27. Double-click the Close button and implement its Click event as follows:
     
    System::Void btnClose_Click(System::Object^  sender, System::EventArgs^  e)
    {
        FileStream ^ stmIceCream = nullptr;
        BinaryWriter ^ bnwIceCream = nullptr;
    
        System::Windows::Forms::DialogResult answer =
    	 MessageBox::Show(L"Do you want to save this order to remember it "
                             L"the next time you come to "
                             L"get your Ice Cream?",
    			 L"Ice Cream Vending Machine",
    			 MessageBoxButtons::YesNo,
    			 MessageBoxIcon::Question);
    
        if( answer == System::Windows::Forms::DialogResult::Yes )
        {
    	 MessageBox::Show(L"In the following form, please enter "
    			  L"your initials and click Save");
    	 FileProcessing ^ frmFileProcessing = gcnew FileProcessing;
    	 frmFileProcessing->lblMessage->Text =
    		 "Enter your initials and click Save";
    	 frmFileProcessing->btnFileProcessing->Text = L"Save";
    	 frmFileProcessing->txtInitials->Text = Initials;
    	 frmFileProcessing->txtInitials->Focus();
    
    	 if( frmFileProcessing->ShowDialog() == 
    		System::Windows::Forms::DialogResult::OK )
    	 {
    	     if( frmFileProcessing->txtInitials->Text == L"" )
    		 MessageBox::Show(L"Invalid File Name: Empty Initials");
    	     else
    	     {
    		 String ^ NameOfFile =
    			 frmFileProcessing->txtInitials->Text + L".icr";
    
    		 try {
    		 stmIceCream = gcnew FileStream(NameOfFile, FileMode::Create);
    		 bnwIceCream = gcnew BinaryWriter(stmIceCream);
    
    		 int Scoops = int::Parse(txtScoops->Text);
    		 double OrderTotal = double::Parse(txtOrderTotal->Text);
    		 bnwIceCream->Write(dtpOrderDate->Value.ToShortDateString());
    		 bnwIceCream->Write(dtpOrderTime->Value.ToShortTimeString());
    		 bnwIceCream->Write(cboFlavors->Text);
    		 bnwIceCream->Write(cboContainers->Text);
    		 bnwIceCream->Write(cboIngredients->Text);
    		 bnwIceCream->Write(Scoops);
    		 bnwIceCream->Write(OrderTotal);
    		 }
    		 finally
    		 {
    		 bnwIceCream->Close();
    		 stmIceCream->Close();
    		 }
    
    		 MessageBox::Show(L"The order has been saved");
    	     }
    	 }
        }
        else
    	 MessageBox::Show("Good Bye: It was a delight serving you");
    
        Close();
    }
  28. Execute the application and test it 
  29. Close the form

 

.NET Framework Exception Handling for File Processing

In the previous lesson of our introduction to file processing, we behaved as if everything was alright. Unfortunately, file processing can be very strict in its assignments. Fortunately, 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 will be asked to work on the file. If the file doesn't exist, the operation cannot be carried. Furthermore, the compiler would throw an error. There are many other exceptions that can be thrown as a result of something going bad during file processing:

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

using namespace System;
using namespace System::IO;

int main()
{
/*    String ^ NameOfFile = L"Members.clb";
	
    FileStream ^ fstPersons = gcnew FileStream(NameOfFile, FileMode::Create);
    BinaryWriter ^ wrtPersons = gcnew BinaryWriter(fstPersons);
        
    try 
    {
        wrtPersons->Write(L"James Bloch");
        wrtPersons->Write(L"Catherina Wallace");
        wrtPersons->Write(L"Bruce Lamont");
        wrtPersons->Write(L"Douglas Truth");
    }
    finally
    {
        wrtPersons->Close();
        fstPersons->Close();
    }*/
    
    String ^ NameOfFile = L"Members.clc";
    String ^ strLine = L"";

    try {
        FileStream ^ fstMembers =
                gcnew FileStream(NameOfFile, FileMode::Open);
        BinaryReader ^ rdrMembers = gcnew 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(L"Error: " + ex->Message);
        Console::WriteLine(L" May be the file doesn't exist " +
                           L"or you typed it wrong!");
    }

    return 0;
}

Here is an example of what this would produce:

Error: Could not find file 'c:\Documents and Settings\Administrator
\My Documents\Visual Studio 2005\Projects\FileProcessing2
\FileProcessing2\Members.clc'. May be the file doesn't exist 
or you typed it wrong!
Press any key to continue . . .

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 Scopes combo box, select IceCream1::Form1 and, in the Functions combo box, select Form1_Load
  2. To throw a FileNotFoundException exception, change the event as follows:
     
    System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)
    {
        Initials = L"";
        FileStream ^ stmIceCream = nullptr;
        BinaryReader ^ bnrIceCream = nullptr;
        FileProcessing ^ frmFileProcessing = gcnew FileProcessing;
    
        frmFileProcessing->lblMessage->Text =
    	 L"Enter your initials and click Open";
        frmFileProcessing->btnFileProcessing->Text = L"Open";
        frmFileProcessing->txtInitials->Text = L"";
        frmFileProcessing->txtInitials->Focus();
    
        if( frmFileProcessing->ShowDialog() == 
    		System::Windows::Forms::DialogResult::OK )
        {
    	 Initials = frmFileProcessing->txtInitials->Text;
    	 String ^ NameOfFile =
    		 frmFileProcessing->txtInitials->Text + L".icr";
    				 
    	 try {
    	    stmIceCream = gcnew FileStream(NameOfFile, FileMode::Open);
    	    bnrIceCream = gcnew BinaryReader(stmIceCream);
    					 
    	    try {
    		 String ^ OrderDate;
    		 String ^ OrderTime;
    		 String ^ SelectedFlavor;
    		 String ^ SelectedContainer;
    		 String ^ SelectedIngredient;
    		 int Scoops;
    		 double OrderTotal;
    
    		 OrderDate = bnrIceCream->ReadString();
    		 OrderTime = bnrIceCream->ReadString();
    		 SelectedFlavor = bnrIceCream->ReadString();
    		 SelectedContainer = bnrIceCream->ReadString();
    		 SelectedIngredient = bnrIceCream->ReadString();
    		 Scoops = bnrIceCream->ReadInt32();
    		 OrderTotal = bnrIceCream->ReadDouble();
    
    		 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.ToString(L"F");
    	    }
    	    finally
    	    {
    		 bnrIceCream->Close();
    		 stmIceCream->Close();
    	    }
    	}
    	catch(FileNotFoundException ^)
    	{
    	    MessageBox::Show(L"It looks like you have not previously "
    		             L"ordered an ice cream here");
    	}
        }
    }
  3. Exercise the application and test it
  4. Close the form
 

Home Copyright © 2007 FunctionX, Inc.