注意:虽然异常后的代码不会执行,但是处理(catch)后的程序会继续执行
示例:
#include <iostream>
using namespace std;
int divide(int a,int b){
if(0==b) throw string("Error:除数不能为0!"); //抛出异常
return a/b;
}
int main(){
int a,b;
cin >> a >> b;
try{
cout << a << '/' << b << '=' << divide(a,b) <<endl;
}
catch (string s){ //捕获异常
cout << s <<endl; //catch处理之后,如果底下还有代码,处理之后会继续
} //执行下去的
}
示例二(构造函数抛出异常):
#include <iostream>
using namespace std;
class Array{
int* data;
public:
Array(int n){
if(n<=0) throw string("Arrary size not <= 0!"); //构造函数抛出异常不会调用析构函数
data = new int[n]; //因为出现异常后,构造都没有进行完成,
} //所以都用不到析构函数
~Array(){
cout << __func__ << endl;
delete [] data;
}
};
void test(){
int n;
cin >> n;
Array Array(n);
}
int main(){
try{
test();
}
catch (string s){
cout << "Error:" << s << endl;
}
}
示例三(成员函数抛出异常):
#include <iostream>
using namespace std;
class Array{
int* data;
int si