在學數據中,發現書上的代碼段中對輸入錯誤的數據進行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;
}