【发布时间】:2014-04-11 12:17:16
【问题描述】:
我正在使用 Visual Studio 2012 构建一个处理输入文件和输出文件的程序。
我是这样实现的:
ifstream inputFile;
ofstream outputFile;
inputFile.exceptions ( ifstream::failbit | ifstream::badbit );
try
{
// some codes here
inputFile.open(inputFileName.c_str());
cout << "Input file opened" << endl;
outputFile.open(outputFileName.c_str());
cout << "Output file opened" << endl;
}
catch (ifstream::failure e)
{
cerr << "Failed to open input file" << endl;
return -1;
}
catch (ofstream::failure e)
{
cerr << "Failed to open output file" << endl;
return -1;
}
并且出现编译错误:
error C2312: 'std::ios_base::failure' : is caught by 'std::ios_base::failure' at line 248
如何使用两个异常源实现 try-catch?
【问题讨论】:
-
这不是一个好主意。您永远不应该将
failbit设置为抛出,因为failbit将设置在文件末尾(并且您不希望文件末尾出现异常)。当您无法打开文件时,您通常不希望出现异常;您想立即处理错误。 -
我发现了。谢谢詹姆斯的建议。
标签: c++ exception try-catch fstream