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 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 the appropriate exception for a closed file error because I deliberately tried to use this method on an already closed file but my "exception !! " comment was not generated.
So what exception should I have written ??
The exception will be thrown when you encounter the EOF because you set ifstream::failbit as exception mask, at least on Mac OS 10.10 Yesomite. If a file is read when EOF is encountered, ios_base::failbit will be set together with ios_base::eofbit .
Exception handling in C++ consist of three keywords: try , throw and catch : The try statement allows you to define a block of code to be tested for errors while it is being executed. The throw keyword throws an exception when a problem is detected, which lets us create a custom error.
The class ofstream is used for output to a file. Both of these classes are defined in the standard C++ library header fstream .
If necessary, the ofstream destructor closes the file for you, but you can use the close function if you need to open another file for the same stream object. The output stream destructor automatically closes a stream's file only if the constructor or the open member function opened the file.
consider following:
void printMe(ofstream& file)
{
file.exceptions(std::ofstream::badbit | std::ofstream::failbit);
try
{
file << "\t"+m_Type+"\t"+m_Id";"+"\n";
}
catch (std::ofstream::failure &e)
{
std::cerr << e.what() << std::endl;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With