Search code examples
c++exceptiontry-catchfstream

Catching an exception for input and output file


I open two files, one input and one output. I'd like to handle exceptions for both of them, so by looking at some examples, I made this:

std::ifstream readFile;
readFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
//set the flags for stream bits that indicate failure if ON
std::ofstream writeFile;
writeFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);


try{
    readFile.open(inputFileName);
    writeFile.open(outputFileName);

    function(readFile, writeFile);

    readFile.close();
    writeFile.close();
}
catch(std::ifstream::failure &readErr) {
    std::cerr << "\n\nException occured when reading a file\n"
              << readErr.what()
              << std::endl;
    return -1;
}
catch(std::ofstream::failure &writeErr) {
    std::cerr << "\n\nException occured when writing to a file\n"
         << writeErr.what()
         << std::endl;
    return -1;
}

This seems like a reasonable solution, but I get a warning:

warning: exception of type 'std::ios_base::failure' will be caught [enabled by default]
     catch(std::ofstream::failure &writeErr) {
     ^

The code does it's thing, but I'm still interested in improving my code. Where have I wronged?


Solution

  • No you can't. The typedef of std::ifstream::failure and std::ofstream::failure are both defined to be std::ios_base::failure.

    The best thing you could do is wrap the individual calls with try-catch:

    try
    {
      readFile.open(inputFileName);
    }
    catch(std::ifstream::failure &readErr) 
    {
    }
    
    try
    {
       writeFile.open(outputFileName);
    }
    catch(std::ofstream::failure &writeErr) 
    {
    }
    

    Or check the state of the streams individually in the catch block to see who failed.