1.异常
void divide(int a, int b)
{
if(b == 0)
throw b;
}
void callDivid(int a, int b)
{
divide(a,b);
}
int main( ){
//尝试去捕获函数异常
try
{
callDivid(10,0);
}
catch(int e) //若捕获到
{
cout << "除数为" << e << "!" << endl;
}
system("pause");
return 0;
}
try
{
}
catch(...)
{
cout << "未知类型异常!" << endl;
}


2.栈解旋
当异常发生时,在throw语句之前在栈上定义的对象都会被自动析构
class MyException{
public:
MyException(){
cout << "构造函数!" << endl;
}
~MyException(){
cout << "析构函数!" << endl;
}
};
int divide(){
MyException ex1, ex2;
cout << "要发生异常了...." << endl;
throw 1;
}
int main(){
try{
divide();
}
catch(int e){
cout << "捕获异常!" << endl;
}
system("pause");
return 0;
}

3.异常接口声明
//这个函数只能抛出int float char三种类型异常,抛出其他的就报错
void func( ) throw(int,float,char){
throw "abc";
}
//不能抛出任何异常
void func02( ) throw(){
throw -1;
}
4.异常对象
class Myexception
{
public:
Myexception()
{
cout<<"构造函数"<<endl;
}
Myexception(const Myexception& m)
{
cout<<"拷贝构造函数"<<endl;
}
~Myexception()
{
cout<<"析构函数"<<endl;
}
};
void test()
{
throw Myexception(); //产生匿名对象
}
void test01()
{
throw &Myexception();
}
void test02()
{
throw new Myexception();
}
int main( ){
try
{
test();
}
catch(Myexception exp) //1.类变量接匿名对象
{
cout<<"捕获到异常"<<endl;
}
try
{
test();
}
catch(Myexception& exp) //2.类引用接匿名对象
{
cout<<"捕获到异常"<<endl;
}
try
{
test01();
}
catch(Myexception *exp) //3.类指针接匿名对象, 问题:随着test01函数结束,导致对象释放
{
cout<<"捕获到异常"<<endl;
}
//解决方法:在堆上分配空间
try
{
test02();
}
catch(Myexception *exp) //3.类指针接匿名对象
{
cout<<"捕获到异常"<<endl;
delete exp;
}
system("pause");
return 0;
}
结果1:

结果2:

结果3:

结果4:
