C++ 中的try-catch异常

代码和讲解如下:

#include<iostream>
using namespace std;

//一、异常基本语法

int divide(int x, int y) {
	if (y==0)
	{
		throw y; //抛异常
	}
	return x / y;
}
void test01() {
	
	//试着去捕获异常
	try {
		divide(10, 0);
	}
	catch (int e) {//异常是根据类型进行匹配
		cout << "除数为" <<e<<"!"<< endl;
	}
}

void deee(int a, int b) {
	try
	{
		divide(a, b);
	}
	catch (int e)
	{
		cout << "除数不能为" << e << endl;
	}
}
void test02() {
	
	deee(10, 0);
}
/*结论:
1,异常可以跨函数 2,有异常必须处理*/

/*二、栈解旋
	异常被抛出后,从进入try块起,到异常被抛出前,在这期间在栈上构造的所有对象,都会被自动析构。析构的顺序与构造的顺序相反,这一过程称为栈的解旋
*/

//异常类
class MyExecption {
public:
	MyExecption() {
		cout << "构造函数" << endl;
	}
	~MyExecption() {
		cout << "析构函数" << endl;
	}
};
int divide() {
	MyExecption ex1, ex2;
	cout << "要发生异常!" << endl;
	throw 1;
}
void test03() {
	try
	{
		divide();
	}
	catch (int e)
	{
		cout << "捕获异常!" << e << endl;
	}
	system("pause");
}
int main(void) {
	test02();
    test03();
	return 0;
}

运行结果
在这里插入图片描述在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43778462/article/details/97618825
今日推荐