如果在输入中,我给出任何字符数据,为什么这不会抛出部分

If in the input I give any character data why this will not going to throw section

本文关键字:为什么 数据 出部 任何 输入 如果 字符      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main()
{
    int x;
    cin>>x;
    cout << "Before try n";
    try {
        cout << "Inside try n";
        if (x <0)
        {
            throw x;
            //cout << "After throw (Never executed) n";
        }
    }
    catch (int x ) {
        cout << "Exception Caught n";
    }
    catch (char x ) {
        cout << "Exception hjCaught n";
    }  
    return 0;
}

如果在输入中,我给出任何字符数据,为什么这不会抛出部分。我的代码是错误的,因为它适用于整数数据类型。

我不明白你为什么添加最后一个catch (char x)子句。

当程序如下所示时:

#include <iostream>
using namespace std;
int main()
{
  int x;
  cin>>x;
  cout << "Before try n";
  try {
    cout << "Inside try n";
    if (x <0)
    {
       throw x;
       //cout << "After throw (Never executed) n";
    }
  }
  catch (int x ) {
    cout << "Exception Caught n";
  }
}

它似乎有效:

  • 正数不会引发异常
  • 负数引发异常

根据该程序,它将在正数时抛出异常。

但是,当您在 int 变量中输入char输入时,将出现输入失败,并且 x 中将出现0

您可以使用它进行检查。

#include <iostream>
using namespace std;
int main()
{
    int x;
    cin >> x;
    if (cin.fail())
    {
        cout << "x is " << x << endl;
    }
    cout << "Before try n";
    try
    {
        cout << "Inside try n";
        if (x < 0)
        {
            throw x;
            //cout << "After throw (Never executed) n";
        }
    }
    catch (int x)
    {
        cout << "Exception Caught n";
    }
    return 0;
}

字符输入上的程序输出将是

一个

x 为 0

在尝试之前

内部尝试

由于 x 将具有 0,因此它不会在条件为 x<0 时引发异常