嘀嘀咕(6)

嘀嘀咕(6)

目录

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;
}

1435096-20181110122332322-1732688996.png

1435096-20181110122340975-1643316919.png

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;
}

1435096-20181110122350759-1526885192.png

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:

1435096-20181110122411320-1778179933.png

结果2:

1435096-20181110122431396-1479659411.png

结果3:

1435096-20181110122449154-1505456191.png

结果4:

1435096-20181110122516409-1532218516.png

posted @ 2018-11-10 12:26 神秘的火柴人 阅读( ...) 评论( ...) 编辑 收藏
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值