1: //exception_classes2.cpp 3: #include <iostream> 4: #include <fstream> 5: #include <string> 6: #include <stdexcept> 7: using namespace std; 9: #include "utilities.h" 10: using scobey::pause; 12: void TestCommandLineArgumentsAndOpenFile 13: ( 14: int argc, //in 15: char* argv[], //in 16: ifstream& inFile //out 17: ); 19: int main(int argc, char* argv[]) 20: { 21: ifstream inFile; 22: TestCommandLineArgumentsAndOpenFile(argc, argv, inFile); 23: inFile.close(); 24: } 26: void TestCommandLineArgumentsAndOpenFile 27: ( 28: int argc, //in 29: char* argv[], //in 30: ifstream& inFile //out 31: ) 32: { 33: try 34: { 35: //Test the command-line arguments 36: if (argc != 4) 37: throw invalid_argument("Error: Program requires 3 arguments."); 39: //Test whether an input file can be opened 40: inFile.open(argv[2]); 41: if (!inFile.is_open()) 42: throw runtime_error("Error: " + string(argv[2]) + " could not be opened."); 43: //If file opened OK, process its contents ... 44: } 45: catch (invalid_argument e) 46: { 47: cout << e.what() << endl; 48: Pause(0, "Program is now terminating."); 49: exit(0); 50: } 51: catch (runtime_error e) 52: { 53: //If something went wrong, close any opened files before terminating 54: inFile.close(); 55: cout << e.what() << endl; 56: Pause(0, "Program is now terminating."); 57: exit(0); 58: } 59: }