Catch exceptions for input and output files


Jab

I open two files, one input and one output. I wanted to handle exceptions for both of them, so by looking at some examples I did:

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 the warning:

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

The code does work, but I'm still interested in improving my code. Where am I wronged?

Yochai Timmer

no, you can not. The type definitions of std::ifstream::failureand std::ofstream::failureboth are defined as std::ios_base::failure.

Your best bet is to wrap each call with a try-catch:

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

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

Or check the status of the stream individually in a catch block to see who failed.

Related