2016-11-08 66 views
-4
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); 

此代码从Discovering modern c++。我不明白“try-block”中的“A”和下一个catch-block中的“e”(cannot_open_file & e)异常在C++中如何工作?

+0

您是按顺序阅读本书吗? – StoryTeller

+0

我怀疑这本书只是在没有解释概念的情况下抛出一段代码。你读到段落结尾了吗? – user463035818

+0

实际上只有这个片段,没有人可以知道'A'究竟是什么,它是一些函数的返回值,它的定义你不会告诉我们(我非常肯定它可以在书中找到)。你可以问一下'x = foo()中'x'的含义;' – user463035818

回答

0

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

0
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++”。查看问题的链接。