![]() |
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:
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. |
|
|
![]() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
| Vanilla Cream of Cocoa Chocolate Chip Cherry Coke Butter Pecan Chocolate Cookie Chunky Butter Organic Strawberry Chocolate Brownies Caramel Au Lait |
| Cone Cup Bowl |
| None Peanuts Mixed Nuts M & M Cookies |
![]() |
||||||||||||||||
|
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();
}
}
}
|
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");
}
}
|
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");
}
|
#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>
}
};
}
|
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();
}
|
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.
|
|
|
||
| Home | Copyright © 2007 FunctionX, Inc. | |
|
|
||