Exception Handling

Intentionally, I have this method, which is written to a file, so I tried to handle the exception of the possibility that I am writing to a closed file:

void printMe(ofstream& file) { try { file << "\t"+m_Type+"\t"+m_Id";"+"\n"; } catch (std::exception &e) { cout << "exception !! " << endl ; } }; 

But apparently std :: exception is not a suitable exception for a closed file error, because I intentionally tried to use this method in an already closed file, but my comment is "exception !!" has not been generated.

So what exception should I write?

+7
source share
2 answers

Streams do not throw exceptions by default, but you can tell them to throw exceptions by calling the file.exceptions(~goodbit) function.

Instead, the usual way to detect errors is to simply check the status of the stream:

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

The reason for this is that there are many common situations where invalid reading is a secondary issue rather than a major one:

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

compared with:

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

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

+12
source

An exception of type ios_base :: failure . However, note that you must set the appropriate flag with ios :: exceptions to throw exceptions, otherwise only internal status flags will be set to indicate an error, which is the default behavior for threads.

+4
source

All Articles