C++异常处理

基本异常处理

1.异常处理机制:暂缓问题处理,不在当前函数中处理,在它调用者中处理

2.任何东西都可以为异常,错误只是异常的一种

3.异常一旦被抛出,不做处理,如果引发异常,会调用默认abort终止程序

4.捕获和处理异常

(1)throw抛出异常

(2)try(检查,捕获)和catch(处理异常)一起出现,{}不可省略

(3)一个try可以对相应多个catch,只能执行一个匹配项

(4)不能存在两个相同的异常处理类型

(5)异常处理中char和int类型不会互相转换

(6)catch(...)处理任何异常类型

(7)throw()和noexcept(函数中不存在抛出异常)

#include <iostream>
using namespace std;
int division(int a,int b)
{
	if (b == 0)
		throw 0;
	return a / b;
}
int main()
{
	try
	{
		division(1 , 0);
	}
	catch (int)
	{
		cout << "除数不能为零" << endl;
	}
	return 0;
}

异常处理中的传参

#include <iostream>
#include <string>
using namespace std;
int division(int a,int b)
{
	if (b == 0)
		throw "除数不能为0";
	if (b == 1)
		throw "除数不能为1";
	if (b == 2)
		throw "除数不能为2";
	return a / b;
}
class err
{
public:
	err(const char* str="未知错位") :str(str){}
	void print()
	{
		cout << str << endl;
	}
protected:
	string str;
};
void insertarr(int arr[], int* cur, int num, int max)
{
	if (*cur >= max)
		throw err("数组下标溢出");
	arr[*cur] = num;
	(*cur)++;
}
int main()
{
	try
	{
		division(1 , 0);
	}
	catch (const char* str)
	{
		cout << str << endl;
	}
	try
	{
		int arr[3] = { 0, 0, 0 };
		int cur = 0;
		for (int i = 0; i < 4; i++)
		{
			insertarr(arr, &cur, i, 3);//数组下标溢出
		}
	}
	catch (err str)
	{
		str.print();
	}
	return 0;
}

标注库的异常

自定义异常

1.自己写异常描述类

2.继承标准库中异常类

#include <exception>
#include <iostream>
using namespace std;
class myexception :public exception
{
public:
	myexception(const char* str) :exception(str){}
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值