#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string filename = "nonexistent_file.txt";
std::ifstream file(filename);
try {
if (!file.is_open()) {
throw std::runtime_error("无法打开文件: " + filename);
}
// 进行文件读取操作,例如读取一行
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
// 关闭文件
file.close();
} catch (const std::exception& e) {
std::cerr << "异常: " << e.what() << std::endl;
}
return 0;
}
- 定义文件名和文件流对象:
std::string filename = "nonexistent_file.txt";
:定义要读取的文件名。
std::ifstream file(filename);
:尝试打开文件,如果文件不存在,file.is_open()
会返回 false
。
- 异常处理部分:
try
块:
if (!file.is_open()) { throw std::runtime_error("无法打开文件: " + filename); }
:检查文件是否成功打开,如果没有成功打开,抛出一个 std::runtime_error
类型的异常,并附带错误信息。
- 在成功打开文件后,进行文件读取操作,这里使用
std::getline
逐行读取文件内容并输出到控制台。
file.close();
:读取完成后关闭文件。
catch
块:
catch (const std::exception& e) { std::cerr << "异常: " << e.what() << std::endl; }
:捕获所有派生自 std::exception
的异常,输出异常信息到标准错误流,以便开发者了解错误原因。