栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++代码:异常处理

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++代码:异常处理

比如我们写了一个数组,通过输入序号,即可得到数组中所在序号的值,但是如果这个序号是负数,或超过数组长度的值,或字母等。

代码如下:

#include
#include

int main() {
	std::vector 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
#include

int main() {
	std::vector 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;
}

结果如下:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1004637.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号