13

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

FruitBreak
  • 570
  • 1
  • 7
  • 19
Joy
  • 1,707
  • 7
  • 29
  • 44

3 Answers3

19

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

Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
  • well I was just tried to get used to exception handling but it's good to know that "Streams don't throw exceptions by default", thanks a lot – Joy Apr 26 '12 at 17:00
6

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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

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;
        }
};
Oleg Kokorin
  • 2,288
  • 2
  • 16
  • 28