捕获输入和输出文件的异常

时间:2014-10-24 07:58:07

标签: c++ exception try-catch fstream

我打开两个文件,一个输入和一个输出。我想处理它们的异常,所以通过查看一些例子,我做了这个:

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;
}

这似乎是一个合理的解决方案,但我收到了警告:

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

代码确实如此,但我仍然对改进代码感兴趣。我在哪里受到冤枉?

2 个答案:

答案 0 :(得分:4)

不,你不能。 std::ifstream::failurestd::ofstream::failure的typedef都定义为std::ios_base::failure

你能做的最好的事情就是用try-catch包裹各个电话:

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

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

或者在catch块中单独检查流的状态,以查看谁失败。

答案 1 :(得分:1)

分别处理这两个文件中的异常的唯一方法是捕获异常,然后检查流上的failbit以确定哪些失败:

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

    function(readFile, writeFile);

    readFile.close();
    writeFile.close();
}
catch (const std::ios_base::failure &err)
{
    if (readFile.fail())
    {
        std::cerr << "\n\nException occured when reading a file\n"
                  << readErr.what()
                  << std::endl;
    }
    if (writeFile.fail())
    {
        std::cerr << "\n\nException occured when writing to a file\n"
                  << writeErr.what()
                  << std::endl;
    }

    return -1;
}