ofstream exception handling

不打扰是莪最后的温柔 提交于 2019-12-04 03:28:17

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

Exception of the type ios_base::failure, However note that you should have set the appropriate flag with ios::exceptions to generate the exceptions or else only internal state flags will be set for indicating the error, which is the default behavior for streams.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!