When will ofstream::open fail?

前端 未结 3 1642
时光说笑
时光说笑 2020-12-03 10:44

I am trying out try, catch, throw statements in C++ for file handling, and I have written a dummy code to catch all errors. My question is in order to check if I have got th

3条回答
  •  抹茶落季
    2020-12-03 11:03

    By default, and by design, C++ streams never throw exceptions on error. You should not try to write code that assumes they do, even though it is possible to get them to. Instead, in your application logic check every I/O operation for an error and deal with it, possibly throwing your own exception if that error cannot be dealt with at the specific place it occurs in your code.

    The canonical way of testing streams and stream operations is not to test specific stream flags, unless you have to. Instead:

    ifstream ifs( "foo.txt" );
    
    if ( ifs ) {
       // ifs is good
    }
    else {
       // ifs is bad - deal with it
    }
    

    similarly for read operations:

    int x;
    while( cin >> x ) {
         // do something with x
    }
    
    // at this point test the stream (if you must)
    if ( cin.eof() ) {
         // cool - what we expected
    }
    else {
         // bad 
    }
    

提交回复
热议问题