1. throw语句和catch语句基本用法示例示例
throw语句用于让开发者人工抛出异常,catch语句捕捉抛出的异常,来继续执行程序
#include<iostream>
#include<vector>
using namespace std;
int main(int argc, char const *argv[])
{
double m,n;
cin >> m>>n;
try{
cout << "before dividing." << endl;
if(n == 0){
throw -1;
}
else
{
cout << m/n << endl;
}
cout << "after dividing." << endl;
}
catch(double d){
cout << "catch(double)" << d <<endl;
}
catch(int e){
cout << "catch(int)" <<e<<endl;
}
//throw出的异常如果被捕捉,try块立即停止执行,程序就会进入catch语句继续执行
//否则直接结束
cout << "finished" << endl;
return 0;
}
2.在main()函数内部来抛出异常
#include<iostream>
#include<vector>
using namespace std;
class CException{
public:
string msg;
CException(string s):msg(s) {}
};
double Divide(double x,double y){
if(y == 0)
throw CException("error:divided by zero.");
cout << "in divide" << endl;
return x / y;
}
int count_tax(int salary){
try
{
if(salary < 0)
throw -1;//抛出异常后后面的语句不再执行
cout << "counting tax" << endl;
}
catch(int)
{
cout << "salary <0" << endl;
}
cout << "tax counted" << endl;
return salary*0.5;
}
int main(){
double f = 1.2;
try{
count_tax(-1);//count_tax会自行处理异常,不会抛给main()函数,所以main()函数不会立即终止
f = Divide(3,0);//Divide函数抛出了异常,会交给main()函数处理
cout << "end of try block" << endl;
}
catch(CException e){
cout << e.msg <<endl;
}
cout << "f=" << f << endl;
cout << "finished" << endl;
return 0;
}
3. 提示信息
int count_tax(int salary){
try
{
if(salary < 0)
throw "zero salary";//抛出异常后后面的语句不再执行
cout << "counting tax" << endl;
}
catch(string s)
{
cout << "error:salary <0" << endl;
//用cout给出error信息
}
cout << "tax counted" << endl;
return salary*0.5;
}