MST

星途 面试题库

面试题:C++中文件操作的异常处理

在C++使用fstream进行文件读取操作时,若文件不存在或读取过程中出现错误,如何进行恰当的异常处理?请写出代码示例并解释每一步的作用。
32.3万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#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;
}
  1. 定义文件名和文件流对象
    • std::string filename = "nonexistent_file.txt";:定义要读取的文件名。
    • std::ifstream file(filename);:尝试打开文件,如果文件不存在,file.is_open() 会返回 false
  2. 异常处理部分
    • 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 的异常,输出异常信息到标准错误流,以便开发者了解错误原因。