Catching appropriate exceptions (reading/writing to a file)

Hello, I would greatly appreciate it if anyone could help me clarify how to tackle "catching appropriate exceptions". I have two functions that currently store and output information to a file. I'm having trouble with catching invalid user input, would this be an appropriate example?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Function that provides the ability to write to a file
void saveVector(string fileName, vector <Vehicle *> vehicles)
{
	size_t i;

	// Ask the user to provide a file name
	cout << "Please provide a file name: ";
	cin >> fileName;

	// 
	ofstream newFile;
	newFile.open("test.txt");

	if (newFile.is_open())
	{
		// For each element in the vector
		for (i = 0; i < vehicles.size(); i++)
		{
			// Store each vehicle element in the file
			newFile << vehicles[i] << endl;
		}

		newFile.close();
	}
	else
	{
		cout << "Unable to create file" << endl;
	}
}

// Function that provides the ability to read a file
void loadVector(string fileName, vector <Vehicle *> vehicles)
{
	// Declare variables and file instance
	size_t i;
	string line;
	ifstream newFile ("test.txt");
	
	// Ask the user to enter a filename to load
	cout << "Enter a current saved filename to read: ";
	cin >> fileName;
	cout << endl;

	// Produce error checking for input loading
	if (newFile.is_open())
	{
		cout << "File opened successfully" << endl << endl;

		//newFile.open(fileName);

		if (newFile.good())
		{
			// For each element in the vector
			for (i = 0; i < vehicles.size(); i++)
			{
				// Call display function to print content in file
				vehicles[i]->display();
			}
		}
		newFile.close();
	}
	else
	{
		// Prompt user with error message
		cout << "Incorrect file name, file opening failed." << endl;
	}
}
Well, There are no "exceptions"(http://www.cplusplus.com/doc/tutorial/exceptions/) being thrown or caught here; when you say exceptions do you want to be using exceptions? Or just handling a bad file name? Because if it is just handling a bad file name, I'd say what you have is a good way to do that. Probably change newFile.open("test.txt"); to newFile.open(fileName.c_str()); though so that you open the file they input.

On a side note, if you're using fileName as a storage from cin, why pass it in as an argument; probably be better to just have it as a temporary variable in the function :P
Yeah you're right, I haven't implemented any exceptions at the moment. I assume you are right with handling a bad file name, as I am being asked to also "catch appropriate exceptions when reading from or writing to a file".

Thanks for your input, I will be sure to try that out. I can't think of any alternatives to meet that criteria. :)
Topic archived. No new replies allowed.