"cin.exceptions"和"exception"在这里是什么意思



我目前是一名工科本科生,对编程有着浓厚的兴趣和热情。这些天我试图通过一些在线参考资料和教程网站来学习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继承。

最新更新