cap*_*tus 1 c++ exception-handling ifstream
我刚刚开始在C++中使用try
和catch
块进行异常处理.我有一个带有一些数据的文本文件,我正在使用ifstream
和阅读此文件getline
,如下所示,
ifstream file;
file.open("C:\\Test.txt", ios::in);
string line;
string firstLine;
if (getline(file, line, ' '))
{
firstLine = line;
getline(file, line);
}
Run Code Online (Sandbox Code Playgroud)
我想知道如何实现异常处理的情况下,file.open
无法打开指定的文件,因为它不会在给定的路径存在,例如没有Test.txt
在C:
R. *_*des 13
默认情况下,iostreams不会抛出异常.相反,他们设置了一些错误标志 您始终可以通过上下文转换为bool来测试上一个操作是否成功:
ifstream file;
file.open("C:\\Test.txt", ios::in);
if (!file) {
// do stuff when the file fails
} else {
string line;
string firstLine;
if (getline(file, line, ' '))
{
firstLine = line;
getline(file, line);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用exceptions
成员函数打开例外.我发现通常情况下,这样做并没有多大帮助,因为你不能再这样做了while(getline(file, line))
:这样的循环只会以异常退出.
ifstream file;
file.exceptions(std::ios::failbit);
// now any operation that sets the failbit error flag on file throws
try {
file.open("C:\\Test.txt", ios::in);
} catch (std::ios_base::failure &fail) {
// opening the file failed! do your stuffs here
}
// disable exceptions again as we use the boolean conversion interface
file.exceptions(std::ios::goodbit);
string line;
string firstLine;
if (getline(file, line, ' '))
{
firstLine = line;
getline(file, line);
}
Run Code Online (Sandbox Code Playgroud)
大多数时候,我不认为在iostream上启用例外是值得的麻烦.API可以更好地解决它们.
归档时间: |
|
查看次数: |
9710 次 |
最近记录: |