我目前是一名工科本科生,对编程有着浓厚的兴趣和热情。这些天我试图通过一些在线参考资料和教程网站来学习C++。但有一个问题我无论如何都无法自己解决。
有人能帮我解释一下cin.exceptions(ios_base::failbit); //throw exception on failbit set
的字面意思吗?
我知道ios_base::failbit
和异常(exception
是STL中的一个类)。
根据我的理解,这意味着当输入不是数字时,它会导致failbit
标志,一旦发生这种情况,系统就会抛出异常。
我很困惑为什么在catch括号中是exception
而不是exceptions
。
//this is a piece of code on my lecture notes
#include <iostream>
#include <string>
using namespace std;
int read_int(const string& prompt);
int main()
{
int n;
n=read_int("Enter a number: ");
cout<<"n: "<<n<<endl;
}
int read_int(const string& prompt){
cin.exceptions(ios_base::failbit);//Why this line "exceptions" different from the next "exception"
int num=0;
while(true){
try{
cout<<prompt;
cin>>num;
return num;
}catch(exception ex)// what does "exception" here mean?
{
cout<<"Bad numeric string--try againn";
cin.clear();
cin.ignore();
}
}
}
在cin.exceptions(...)
中,exceptions是一个函数名。特别是这个函数,让我们为流设置一个新的异常掩码。
在catch(exception ex)
中,exception是一个类型名称。特别是作为异常的基本类型的类型CCD_ 9。在这种情况下,这意味着您将捕获任何异常,因为它们都应该从exception
继承。