Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ofstream exception handling

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 ??

like image 966
Joy Avatar asked Apr 26 '12 16:04

Joy


People also ask

Does ofstream throw exception?

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 .

How is exception handling done in C++?

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.

Where is ofstream defined C++?

The class ofstream is used for output to a file. Both of these classes are defined in the standard C++ library header fstream .

Does ofstream destructor close file?

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.


1 Answers

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;
        }
};
like image 198
Oleg Kokorin Avatar answered Oct 21 '22 04:10

Oleg Kokorin