【问题标题】:Catching an exception for input and output file捕获输入和输出文件的异常
【发布时间】:2014-10-24 07:58:06
【问题描述】:

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

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) {
     ^

代码可以做到这一点,但我仍然有兴趣改进我的代码。我哪里错了?

【问题讨论】:

  • 总是通过 const 引用捕获异常:catch(const std::ofstream::failure &amp;writeErr) {
  • 怎么会,有影响吗?
  • 您的设置位和捕获的异常都不在std::ifstream 和std::ofstream 中。它们植根于 both 的基本层次结构中的std::ios_base。 IE。 std::ifstream::failure 和 std::ofstream::failure 都是实际上是 std::ios_base::failure。因此,您两次捕获了相同的异常。
  • 没有办法分开吗?
  • 我从未尝试过,而且我真的很想看看有这样的机制。我最初的反应是不,而不是将操作嵌套在它们自己的 try-catch 块中。 (这需要在您的代码中的function 中完成)。

标签: c++ exception try-catch fstream


【解决方案1】:

不,你不能。 std::ifstream::failure和std::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 块中单独检查流的状态,看看谁失败了。

【讨论】:

  • 我认为在第二个 catch 块中,您的意思是“std::ofstream::failure &writeErr”,不是吗?我可能在这里误解了你,所以我要求确保我没有完全遗漏一些明显的东西。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    相关资源
    最近更新 更多