尝试捕获异常处理C++

Try catch exception handling C++

本文关键字:异常处理 C++      更新时间:2023-10-16

我刚刚开始使用trycatch块在C++中进行异常处理。我有一个包含一些数据的文本文件,我正在使用ifstreamgetline读取此文件,如下所示,

ifstream file;
file.open("C:\Test.txt", ios::in);
string line;
string firstLine;
if (getline(file, line, ' '))
{
    firstLine = line;
    getline(file, line);
}

我想知道如何在file.open无法打开指定文件的情况下实现异常处理,因为它在给定路径中不存在,例如C:中没有Test.txt

默认情况下,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);
    }
}

您可以使用 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);
}

大多数时候,我认为在iostreams上启用例外是不值得的。API 在关闭它们时效果更好。

IOstreams 为您提供了为各种状态位打开异常的选项。参考有一个非常清晰的例子,这正是您所要求的。

好吧,如果文件不存在,这完全取决于您要做什么。

当前的代码(假设这是main(将退出进程。

但是,如果这是一个函数调用,那么您可能希望围绕对此函数的调用添加异常处理。

例如

try
{
    OpenAndReadFile( std::string filename );
}
catch ( std::ifstream::failure e )
{
    // do soemthing else
}
catch ( OtherException e )
{
}
catch ( ... )
{
    // All others
}

这假设为ifstream打开了异常引发。