C++ 丟擲並捕獲多個異常
阿新 • • 發佈:2019-02-16
// Project20161020.cpp : 定義控制檯應用程式的入口點。 // #include "stdafx.h" #include<iostream> #include<exception> #include<fstream> #include<string> #include<vector> using namespace std; /** 丟擲並捕獲多個異常 */ void readIntegerFile(const string& fileName, vector<int> &dest) { ifstream istr; int temp; istr.open(fileName); if (istr.fail()) { throw runtime_error("Unable to open the file"); } while (istr >> temp) { dest.push_back(temp); } if (!istr.eof()){ //We did not reach the end-of-file //This means that some error occurred while reading the file //Throw an exception //檔案結尾是非數字 則丟擲 throw runtime_error("Error reading the file."); } } int main() { vector<int> myInts; const string& fileName = "C:/Users/Administrator/Desktop/IntegerFile.txt"; try { readIntegerFile(fileName, myInts); } catch (const exception e) { cerr << e.what() << endl; return 1; } for (const auto element : myInts) { cout << element << " "; } cout << endl; return 0; }
#include "stdafx.h" #include<iostream> #include<stdexcept> #include<fstream> #include<string> #include<vector> using namespace std; /** 也可以讓readIntegerFile()丟擲兩種不同型別的異常。以下是實現 如果不能開啟檔案,則丟擲invalid_argument類異常物件,如果無法讀取整數,就丟擲runtime_error類物件。 invalid_argument和runtime_error都是定義在<stdexcept>標頭檔案中的類 */ void readIntegerFile(const string& fileName, vector<int> &dest) { ifstream istr; int temp; istr.open(fileName); if (istr.fail()) { throw invalid_argument("Unable to open the file"); } while (istr >> temp) { dest.push_back(temp); } if (!istr.eof()) { //We did not reach the end-of-file //This means that some error occurred while reading the file //Throw an exception //檔案結尾是非數字 則丟擲 throw runtime_error("Error reading the file."); } } int main() { vector<int> myInts; const string& fileName = "C:/Users/Administrator/Desktop/IntegerFile.txt"; //main()函式可以用兩個catch語句捕獲invalid_argument和runtime_error try { readIntegerFile(fileName, myInts); } catch (const invalid_argument& e) { cerr << e.what() << endl; return 1; } catch (const runtime_error& e) { cerr << e.what() << endl; return 1; } for (const auto&element : myInts) { cout << element << " "; } cout << endl; return 0; }