原创 linux下c++ lesson16异常处理机制

28 篇文章 0 订阅
本文详细介绍了在Linux系统中使用C++进行异常处理的基本语法、思想、声明、异常对象以及标准异常库的运用,通过五个部分深入探讨C++异常处理机制。
摘要由CSDN通过智能技术生成

1-异常基本语法.cpp

#include <iostream>

using namespace std;

int Div(int x, int y)
{
	if (0 == y)
	{
		//return -1;
		//throw 0;        //抛出异常
		throw 'a';
	}

	return x / y;
}

int main()
{
	int a, b;

	cin >> a >> b;

	try{ 								//把可能抛出异常的代码放在try语句中
		cout << Div(a, b) << endl;
	}
	catch(int)
	{
		cout << "zero exception" << endl;
	}
	catch (char)
	{
		cout << "char exception" << endl;
	}

	return 0;
}

2-异常的思想.cpp

#include <iostream>

using namespace std;

int DDiv(int x, int y)
{
	if (0 == y)
	{
		throw 0;
	}
	return x / y;
}

int Div(int x, int y)
{
	/*int ret = DDiv(x, y);
	if (0 == ret)
	{	
	}
	else
	{
	}*/

	return DDiv(x, y);
}

int main()
{
	int a, b;

	cin >> a >> b;

	try{ 								//把可能抛出异常的代码放在try语句中
		cout << Div(a, b) << endl;
	}
	catch(int)
	{
		cout << "zero exception" << endl;
	}
	catch (char)
	{
		cout << "char exception" << endl;
	}

	return 0;
}

3-异常声明.cpp

#include <iostream>

using namespace std;

int Div(int x, int y) throw(int, char);   //只能抛出整形或者字符型异常
//int Div(int x, int y) throw();          //不会抛出任何类型异常
//int Div(int x, int y);                  //可能抛出任何类型的异常

int main()
{
	int a, b;

	cin >> a >> b;

	try{ 								//把可能抛出异常的代码放在try语句中
		cout << Div(a, b) << endl;
	}
	catch(int)
	{
		cout << "zero exception" << endl;
	}
	catch (char)
	{
		cout << "char exception" << endl;
	}

	return 0;
}

int Div(int x, int y) throw(int, char)
{
	if (0 == y)
	{
		//return -1;
		//throw 0;        //抛出异常
		throw 'a';
	}

	return x / y;
}

4-异常对象.cpp

#include <iostream>

using namespace std;

class Test
{
public:
	Test()
	{	
		cout << "Test构造函数" << endl;
	}
	Test(const Test &t)
	{
		cout << "Test拷贝构造函数" << endl;
	}
	void print()
	{
		cout << "Test Exceotion" << endl;
	}
	~Test()
	{
		cout << "Test析构函数" << endl;
	}
};

int Div(int x, int y)
{
	if (0 == y)
	{
		throw Test();    //抛出对象
		//throw new Test;    //抛出对象指针
	}

	return x / y;
}

int main()
{
	int a, b;

	cin >> a >> b;

	try{ 								//把可能抛出异常的代码放在try语句中
		cout << Div(a, b) << endl;
	}
	catch(int)
	{
		cout << "zero exception" << endl;
	}
	catch (char)
	{
		cout << "char exception" << endl;
	}
	/*catch (Test t)   //调用拷贝构造函数
	{
		t.print();
	}*/
	catch (Test &t)   //推荐
	{	
		t.print();
	}
	catch (Test *t)
	{
		t->print();
		delete t;   //需要手动释放
	}

	return 0;
}

5-标准异常库.cpp

#include <iostream>
#include <exception>

using namespace std;

int main()
{
	try{
		int *p = new int[-1];
	}
	catch (exception &e)
	{
		cout << e.what() << endl;
	}

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值