溫馨提示×

read在c++中的異常處理

c++
小樊
107
2024-08-28 02:18:36
欄目: 編程語言

在C++中,read() 函數通常用于從文件或其他輸入流中讀取數據

以下是一個使用 std::ifstream 和異常處理的示例:

#include<iostream>
#include <fstream>
#include<string>

int main() {
    std::ifstream file("example.txt");

    if (!file) {
        std::cerr << "Error opening file."<< std::endl;
        return 1;
    }

    std::string line;

    try {
        while (std::getline(file, line)) {
            // Process the line
        }
    } catch (const std::ios_base::failure& e) {
        std::cerr << "I/O error: " << e.what()<< std::endl;
        return 1;
    } catch (...) {
        std::cerr << "Unknown exception caught while reading the file."<< std::endl;
        return 1;
    }

    file.close();

    return 0;
}

在這個示例中,我們首先檢查文件是否成功打開。如果打開失敗,我們將輸出錯誤消息并返回非零值。然后,我們使用 try 塊來讀取文件的每一行。如果在讀取過程中發生 I/O 錯誤,我們將捕獲 std::ios_base::failure 異常并輸出相應的錯誤消息。如果捕獲到其他類型的異常,我們將輸出一個通用的錯誤消息。最后,我們關閉文件并返回 0。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女