如果在输入中,我给出任何字符数据,为什么这不会抛出部分
If in the input I give any character data why this will not going to throw section
#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 时引发异常
相关文章:
- 为什么复制而不是移动数据元素?
- 为什么C中的通用链表中存储的数据已损坏
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 为什么字符串的 move() 会改变内存中底层数据的位置?
- 为什么我们使用在C++中返回数据结构的函数?
- 为什么基类数据在派生类数据之前初始化
- 为什么当我尝试搜索双链表中第一个数据条目之外的数据时,程序崩溃了?
- 为什么我们需要在链接列表链接之前填写数据?
- 大家好,当一个类有一个向量作为它的数据成员时,为什么它的大小总是24?
- 为什么添加延迟会提高此多线程环境中的数据吞吐量?
- 为什么双精度数据类型在C++中出错?
- 为什么数据不传输
- 为什么数据中的随机部分替换了曾经存储在我的角色数组中的其他数据
- 为什么数据类型转换错误只出现在C++中而不出现在C中
- 为什么数据类型的大小会随着操作系统的变化而变化
- 为什么数据类型 long 支持的最大数量等于 long long?
- 为什么数据断点不能在未对齐的地址上工作
- 为什么数据成员的模板功能仅在符合"this"时才是依赖名称?
- 二进制比较的结果简化为什么数据类型
- 为什么数据实例在默认情况下不为 NULL?