#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;
}