2020.11.15 第9课 C++异常处理机制

本文详细介绍了C++的异常处理机制,包括基本异常处理、异常处理中的参数传递、自定义异常类型、标准库异常类的使用、异常类的继承、函数模板、类模板以及模板的嵌套应用,特别是重写了标准库异常类的what方法。
摘要由CSDN通过智能技术生成

2020.11.15 第9课 C++异常处理机制

一、基本异常处理

----------------------------------------------------------
	throw:抛出异常
	try:检查异常			
	catch:捕获处理异常
	1.任何东西都可以当作异常
		错误也是异常的一种
	2.异常处理机制
		问题不在当前函数解决
	3.抛出的异常,不处理,如果引发异常,会调用默认处理abort终止程序
	4.try和catct不许是一起出现,必须{
   }
----------------------------------------------------------
#include <iostream>
using namespace std;
int divisor(int a, int  b)
{
   
	if (b == 0)
	{
   
		throw 1.1;
	}
	return a / b;
}
int main()
{
   
	try								//类似于跳转语句
	{
   
		cout << divisor(1, 0) << "Iloveyou" << endl;
		cout << "LZG" << endl;
	}
	catch (int) //捕获抛出的数据类型   综合管理同一种数据的问题
	{
   
		cout << "除数不能为零" << endl;
	}
	catch (double)
	{
   
		cout << "除数不能为零" << endl;
	}
	return 0;
}

二、异常处理中的传参过程

#include <iostream>
using namespace std;
int divisor(int a, int b)
{
   
	if (b == 0)
		throw "除数不能为零";
	return a / b;
}
void print(int a)
{
   
	if (a == 0)
		throw a;
	cout << a << endl;
}
int main()
{
   
	try
	{
   
		divisor(1, 0);
	}
	catch (const char* object)		//const char* objenct=抛出的值
	{
   
		//cout << "除数不能为零" << endl;
		cout << object << endl;
	}
	try
	{
   
		print(0);
	}
	catch(int a)
	{
   
		cout << a << endl;
	}
	//可以捕获任何抛出的东西      任何类型  删减符
	try
	{
   
		divisor(1, 0);
	}
	catch (...)	
	{
   
		cout << "捕获任何异常" << endl;
	}
	return 0;
}

三、抛出自定义类型的数据

----------------------------------------------------------
	链式栈
	链表为NULL
	栈为NULL
----------------------------------------------------------
#include <iostream>
using namespace std;
class ListEmpty
{
   
public:
	ListEmpty(string str = "栈不能为NULL"): str(str){
   }
	void print()
	{
   
		cout << str << endl;
	}
protected:
	string str;
};
class List
{
   
public:
	void pop_back()
	{
   
		if (0)
			throw ListEmpty(); //抛出的是一个无名无参对象 返回的是
	}
	void pop_front()
	{
   
		if (1)
			throw ListEmpty("无名对象");		//无名有参
	}
protected:

};
int main()
{
   
	List* pList = new List;
	try
	{
   
         pList->pop_back();		//异常处理综合管理
		pList->pop_front();		
	}
	catch (ListEmpty object)
	{
   
		object.print
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值