1: //errors_exceptions.cpp
2: //Illustrates use of "exception handling" to handle errors encountered
3: //in attempting to read data from a file input stream.
5: #include <iostream>
6: #include <fstream>
7: using namespace std;
9: #include "utilities.h"
10: using Scobey::Pause;
12: int main()
13: {
14: cout << "\nThis program tries to open a file input stream, "
15: "then read two integers from it,\nand display them. If it "
16: "does not succeed, it reports an error and terminates.\n";
17: Pause();
19: enum ExceptionList
20: {
21: OPENING_FILE_EXCEPTION,
22: READING_FILE_EXCEPTION
23: };
25: ifstream inFile;
27: try
28: {
29: inFile.open("exceptions.in");
30: if (!inFile.is_open()) throw OPENING_FILE_EXCEPTION;
32: int first, second;
33: inFile >> first >> second;
34: if (!inFile) throw READING_FILE_EXCEPTION;
36: cout << "The file was actually read. "
37: "The two values in it were: \n"
38: << " first: " << first
39: << " second: " << second << "\n\n";
40: }
42: catch (ExceptionList e)
43: {
44: switch (e)
45: {
46: case OPENING_FILE_EXCEPTION:
47: Pause(0, "Error: Could not open input data file "
48: "\"exceptions.in\".\nMake sure file exists, "
49: "and run program again.");
50: return 1;
51: case READING_FILE_EXCEPTION:
52: if (inFile.eof())
53: Pause(0, "Error: End of file reached before "
54: "all data read.\nProgram now terminating.");
55: else
56: Pause(0, "Error: Something wrong with input data."
57: "\nProgram now terminating.");
58: return 2;
59: }
60: }
61: Pause();
62: }