尝试catch异常处理C ++ [英] Try catch exception handling C++
问题描述
我刚刚开始使用 try
和 catch
块中的异常处理。我有一个文本文件与一些数据,我正在使用 ifstream
和 getline
读取此文件,如下所示, p>
I have just started with exception handling in C++ using try
and catch
blocks. I have a text file with some data and I am reading this file using ifstream
and getline
as shown below,
ifstream file;
file.open("C:\\Test.txt", ios::in);
string line;
string firstLine;
if (getline(file, line, ' '))
{
firstLine = line;
getline(file, line);
}
我想知道如何实现异常处理 file.open
无法打开指定的文件,因为它在给定路径中不存在,例如没有 Test.txt
C:
I would like to know how to implement exception handling in case file.open
fails to open the specified file because it does not exist in the given path, for example there is no Test.txt
in C:
推荐答案
默认情况下,iostreams不会抛出异常。相反,他们设置一些错误标志。您可以随时测试上一个操作是否成功通过上下文转换为bool:
By default iostreams do not throw exceptions. Instead they set some error flags. You can always test if the previous operation succeeded with a contextual conversion to 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);
}
}
您可以使用 异常
成员函数。我发现更多的时候,这不会帮助太多,因为你不能再像 while(getline(file,line))
:这样的循环只有退出异常。
You can turn on exceptions with the exceptions
member function. I find that more often than not, doing this doesn't help much because you can no longer do things like while(getline(file, line))
: such an loop would only exit with an exception.
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);
}
大多数时候,我不认为启用iostreams的例外是值得的麻烦。 API的效果更好。
Most of the time, I don't think enabling exceptions on iostreams is worth the hassle. The API works better with them off.
这篇关于尝试catch异常处理C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!