#include <iostream>
#include <fstream>
int main() {
try {
std::ifstream file("test.txt");
if (!file) {
throw std::runtime_error("Failed to open file");
}
// code to read from file
} catch (const std::exception& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
good()
、fail()
、bad()
和eof()
成員函數來檢查流的狀態。#include <iostream>
#include <fstream>
int main() {
std::ifstream file("test.txt");
if (!file.is_open()) {
std::cerr << "Failed to open file" << std::endl;
return 1;
}
// code to read from file
if (file.fail()) {
std::cerr << "Failed to read from file" << std::endl;
return 1;
}
return 0;
}
std::ios_base::iostate
類型的異常規范來指定在發生錯誤時是否拋出異常。#include <iostream>
#include <fstream>
int main() {
std::ifstream file("test.txt");
file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
// code to read from file
} catch (const std::ios_base::failure& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
clear()
函數來清除流的錯誤狀態,以便繼續進行輸入輸出操作。#include <iostream>
#include <fstream>
int main() {
std::ifstream file("test.txt");
if (file.fail()) {
std::cerr << "Failed to open file" << std::endl;
file.clear(); // clear the error state
}
// code to read from file
return 0;
}