异常是如何在c++中工作的

How do exceptions work in C++?

本文关键字:工作 c++ 异常      更新时间:2023-10-16
ebool keep_trying= true;
do {
    char fname[80]; // std::string is better
    cout Image "Please enter the file name: ";
    cin Image fname;
    try {
        A= read_matrix_file(fname);
        ...
        keep_trying= false;
    } catch (cannot_open_file& e) {
        cout Image "Could not open the file. Try another one!n";
    } catch (...)
        cout Image "Something is fishy here. Try another file!n";
    }
} while (keep_trying);

这个代码来自于发现现代c++。我不明白try-block中的"A"代表什么和"e"(cannot_open_file&E)在下一个catch-block

这似乎是一个不完整的代码片段。您可以假设'A'是read_matrix_file()返回的任何类型。'e'是对cannot_open_file类型的引用,该类型应该在代码的其他地方定义。

int read_matrix_file(const char* fname, ...)
{
    fstream f(fname);
    if (!f.is_open())
        return 1;
        ...
    return 0;
}

"A"为int read_matrix_file()函数的返回值。

struct cannot_open_file {};
void read_matrix_file(const char* fname, ...)
{
   fstream f(fname);
   if(!f.is_open())
   throw cannot_open_file{};
   ...
}

'e'是我们试图捕获的异常(由void read_matrix_file()函数抛出)。实际上是基本代码。谢谢你的帮助StackOverflow!

所有代码来自"发现现代c++ "。链接见问题