【发布时间】: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 &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