C++中用try catch抛出异常

在学数据中,发现书上的代码段中对输入错误的数据进行throw 处理,以前没搞懂,现在查资料弄一弄。

这是线性表插入的代码

void List::insert(int n,int x)
{
	if(n<1||n>100)throw"溢出";
	if(n>=len)throw"位置"; 
	for(int i=len-1;i>=n-1;i--)
	{
		data[i+1]=data[i];
	}
	data[n-1]=x;
	len++;
}

try catch的用法:

    首先对代码段分块,可能发生错误的代码写在try后,并用{}包起来。接着写catch{},大括号内用cerr输出错误原因.(在发生错误的地方throw 返回),以下是代码

#include<iostream>
#include<stdlib.h>//必要的头文件 
using namespace std;
double fun(double n,double m)//除法 
{
	if(m==0)
	throw n;
	else
	return n/m;
}
int main()
{
	double x;
	try{
		x=fun(4,2);
		cout<<"x的值为"<<x<<endl;//正常输出 
		x=fun(4,0);//发生错误 
	}
	catch(double)
	{
		cerr<<"发生错误:除数为0"<<endl;
		exit(1);
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/hwj729748198/article/details/79783526
今日推荐