C++ 异常在C+中如何工作+;?
此代码来自。我不明白try块中的“A”代表什么,下一个catch块中的“e”(无法打开文件&e)代表什么,这似乎是一个不完整的代码片段。您可以假设“A”是read\u matrix\u file()返回的任何类型。“e”是对无法打开文件类型的引用,应该在代码中的其他地方定义C++ 异常在C+中如何工作+;?,c++,c++11,exception-handling,C++,C++11,Exception Handling,此代码来自。我不明白try块中的“A”代表什么,下一个catch块中的“e”(无法打开文件&e)代表什么,这似乎是一个不完整的代码片段。您可以假设“A”是read\u matrix\u file()返回的任何类型。“e”是对无法打开文件类型的引用,应该在代码中的其他地方定义 ebool keep_trying= true; do { char fname[80]; // std::string is better cout Image "Please enter the file
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);
“A”是int read\u matrix\u file()函数的返回值
int read_matrix_file(const char* fname, ...)
{
fstream f(fname);
if (!f.is_open())
return 1;
...
return 0;
}
“e”是我们试图捕获的异常(由void read\u matrix\u file()
函数引发)。实际上是基本代码。
谢谢你的帮助
所有代码都来自“发现现代C++”。请参阅链接问题。您是否按顺序阅读了本书?我怀疑本书在没有解释概念的情况下只是向您抛出了一段代码。你读到这一段的结尾了吗?事实上,只有这段代码,没有人知道A
到底是什么,它是某个函数的返回值,你没有告诉我们它的定义(我很确定它可以在书中找到)。你也可以问x=foo()中x
的含义是什么代码>是的,这本书只是抛出了代码。是的,我是按顺序阅读的,我想跳过这一部分,因为我没有真正理解它,当我测试代码时,它不起作用。有人知道第一个cath块中的“e”代表什么吗?
struct cannot_open_file {};
void read_matrix_file(const char* fname, ...)
{
fstream f(fname);
if(!f.is_open())
throw cannot_open_file{};
...
}