关键词搜索

源码搜索 ×
×

C++中的try catch

发布2014-10-19浏览7552次

详情内容

        先来看一个简单的程序:

 

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int a = 100;
  6. int b = 0;
  7. int c = 0;
  8. for(b = -1; b <= 1; b++)
  9. {
  10. try
  11. {
  12. c = a / b;
  13. // 因为b为0, 出现异常, 所以下面语句不会执行
  14. cout << "try" << endl;
  15. }
  16. catch(...)
  17. {
  18. cout << "catch" << endl;
  19. }
  20. cout << "out" << endl;
  21. }
  22. return 0;
  23. }

        结果为:

 

try
out
catch
out
try
out

 

       上面程序利用了C++中的异常机制,我们再来看两个程序:

 

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int *p = NULL;
  6. //try
  7. {
  8. *p = 0;
  9. cout << "try" << endl;
  10. }
  11. //catch(...)
  12. {
  13. cout << "catch" << endl;
  14. }
  15. return 0;
  16. }

     运行时会出错, 大忌啊。 需要改为如下:

 

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int *p = NULL;
  6. try
  7. {
  8. *p = 0;
  9. cout << "try" << endl;
  10. }
  11. catch(...)
  12. {
  13. cout << "catch" << endl;
  14. }
  15. return 0;
  16. }

      结果为:catch

 

      异常机制在实际开发中, 会经常见到, 可以增强程序的稳健性。

 

 

相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载