C++ Stream的错误处理技巧

   2024-10-06 8940
核心提示:使用try-catch语句块捕获异常:在使用C++ Stream进行输入输出操作时,可以在可能抛出异常的代码块中使用try-catch语句块来捕获异

使用try-catch语句块捕获异常:在使用C++ Stream进行输入输出操作时,可以在可能抛出异常的代码块中使用try-catch语句块来捕获异常并进行相应的处理。

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号