ofstream exception handling

前端 未结 3 1333
梦毁少年i
梦毁少年i 2021-02-19 19:53

Deliberately I\'m having this method which writes into a file, so I tried to handle the exception of the possiblity that I\'m writing into a closed file:

void pr         


        
3条回答
  •  眼角桃花
    2021-02-19 20:47

    Streams don't throw exceptions by default, but you can tell them to throw exceptions with the function call file.exceptions(~goodbit).

    Instead, the normal way to detect errors is simply to check the stream's state:

    if (!file)
        cout << "error!! " << endl ;
    

    The reason for this is that there are many common situations where an invalid read is a minor issue, not a major one:

    while(std::cin >> input) {
        std::cout << input << '\n';
    } //read until there's no more input, or an invalid input is found
    // when the read fails, that's usually not an error, we simply continue
    

    compared to:

    for(;;) {
        try {
            std::cin >> input;
            std::cout << input << '\n';
        } catch(...) {
            break;
        }
    }
    

    See it live: http://ideone.com/uWgfwj

提交回复
热议问题