C++复习笔记--异常处理

C++语言异常处理机制的基本思想是将异常的检测与处理分离。

C++使用throw和try-catch语句支持异常处理,分以下三步:

(1)检查异常(使用try语句块)。

(2)抛出异常(使用throw语句块)。

(3)捕捉异常(使用catch语句块)。

throw 表达式;
try {
	被检查的语句;
}
catch(异常信息类型){
	进行异常处理的语句;
}

看例子最容易理解:

#include<iostream>
using namespace std;

int Divide(int x, int y) {
	if (y == 0) throw y;    //如果分母为0,抛出异常
	return x / y;
}

int main() {
	int a = 10, b = 5, c = 0;
	try {       //检查是否出现异常
		cout << "a/b=" << Divide(a, b) << endl;
		cout << "b/a=" << Divide(b, a) << endl;
		cout << "a/c=" << Divide(a, c) << endl;
		cout << "c/b=" << Divide(c, b) << endl;
	}
	catch (int) {  //捕获异常并处理,即输出一条提示信息
		cout << "except of divide zero" << endl;
	}
	cout << "calculate finished" << endl;
	return 0;
}

注意:这个结果输出的没有第四句的执行结果,也是就是说第三局执行语句出现问题之后,抛出异常的时候就跳出了这个try语句,后面的不再执行。


编写程序,从键盘上输入一个学生的姓名(建议用string类型)、年龄(合理的年龄在15~25之间,五分制考试分数(合理范围在0~5分之间),调用函数float CheckAgeScore(int age,float score),该函数主要完成两件事:通过检查两个形式参数的范围是否合理,抛出不同的异常信息;如果无异常,则返回对应的百分之成绩。主函数中定义try-catch结构检测、捕获并处理异常。最后输出该同学的姓名、年龄、百分之成绩。

#include<iostream>
#include<string>
using namespace std;

float CheckAgeScore(int age, float score) {
	if (age < 15 || age>25)
		throw age;
	if (score < 0 || score>5)
		throw score;
	return score * 20;
}
int main() {
	string name;
	int age;
	float score;
	cin >> name >> age >> score;
	try {
		cout << name << ": " << age << " " << CheckAgeScore(age,score) << endl;
	}
	catch (int) {
		cout << "年龄不符。" << endl;
	}
	catch (float) {
		cout << "分数有误。" << endl;
	}
	return 0;
}

这段程序的结果不在贴出,自行测试。

发布了51 篇原创文章 · 获赞 5 · 访问量 2014

猜你喜欢

转载自blog.csdn.net/MARS_098/article/details/103671841