比如我们写了一个数组,通过输入序号,即可得到数组中所在序号的值,但是如果这个序号是负数,或超过数组长度的值,或字母等。
代码如下:
#include<iostream>
#include<vector>
int main() {
std::vector<int> myV = { 32,14,73,28,41,38,92 };
int index = -1;
std::cout << "Please input an Integer:" << std::endl;
std::cin>>index;
std::cout << "The index is:" << index << std::endl;
std::cout << "The item is:" << myV[index] << std::endl;
return 0;
}
如果我们使用的是-3,但是输出会直接终止。
那么如何通过异常处理呢
代码如下:
#include<iostream>
#include<vector>
int main() {
std::vector<int> myV = { 32,14,73,28,41,38,92 };
int index = -1;
while (true)
{
std::cout << "Please input an Integer:" << std::endl;
try {
if (std::cin >> index && std::cin.get() == '\n') {
if (index < 0) { break; }
else {
if (index >= myV.size()) {
throw - 2;
}
else {
std::cout << "The index is:" << index << std::endl;
std::cout << "The item is:" << myV[index] << std::endl;
}
}
}
else {
std::cin.clear();
std::cin.ignore(INTPTR_MAX, '\n');
throw - 3;
}
}
catch (int e) {
if (e == -2) {
std::cout << "The value is bigger than index." << std::endl;
}
else if (e == -3) {
std::cout << "The input is not an integer." << std::endl;
}
}
}
return 0;
}
结果如下: