C++ 捕获异常

throw 要写在try 中 ,throw 出的异常,由catch 接住,然后做相应的处理


C++异常机制使用了三个新的关键字 


try    ──标识可能出现的异常代码段


throw  ──抛出一个异常


catch  ──标识处理异常的代码段


 


提示:


 使用异常处理将带来更多的系统开销。因此慎用异常。


二、抛出异常


throw


throw必须在 try代码块中.后边跟的值决定抛出异常的类型。


三、捕获异常


catch 

 

出现在try代码块后,后边跟的数据决定捕获的类型


catch(...) //表示捕获所有异常


int _tmain(int argc, _TCHAR* argv[])

{
int a,b;
a =333;
b=0;
try
{
if (b ==0)
{
throw "error b should not be zero";
//throw 1;
}
printf("%d", a/b);
}
catch(char *s)
{
cout<<s<<endl;
}
catch(exception e)
{


}
catch( int i)
{
cout<<i<<endl;


}
catch(...)
{
cout<<"error"<<endl;
}

return 0;
}
//throw 1;
}
printf("%d", a/b);
}
catch(char *s)
{
cout<<s<<endl;
}
catch(exception e)
{

}
catch( int i)
{
cout<<i<<endl;


}
catch(...)
{
cout<<"error"<<endl;
}

return 0;
}
}
catch( int i)
{
cout<<i<<endl;


}
catch(...)
{
cout<<"error"<<endl;
}

return 0;
}
}
catch( int i)
{
cout<<i<<endl;

}
catch(...)
{
cout<<"error"<<endl;
}

return 0;
}
}
catch(...)
{
cout<<"error"<<endl;
}

return 0;
}
}
catch(...)
{
cout<<"error"<<endl;
}
return 0;
}
return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值