cpp 专题
专题目录
您的位置:cpp > cpp 专题 > C++ try/catch语句
C++ try/catch语句
作者:--    发布时间:2019-11-20

在c++编程中,使用try/catch语句执行异常处理。 c++ try块用于放置可能发生异常的代码。catch块用于处理异常。

没有try/catch的示例

#include <iostream>  
using namespace std;  
float division(int x, int y) {  
   return (x/y);  
}  
int main () {  
   int i = 50;  
   int j = 0;  
   float k = 0;  
      k = division(i, j);  
      cout << k << endl;  
   return 0;  
}

执行上面代码得到以下结果 -

floating point exception (core dumped)

c++ try/catch示例

#include <iostream>  
using namespace std;  
float division(int x, int y) {  
   if( y == 0 ) {  
      throw "attempted to divide by zero!";  
   }  
   return (x/y);  
}  
int main () {  
   int i = 25;  
   int j = 0;  
   float k = 0;  
   try {  
      k = division(i, j);  
      cout << k << endl;  
   }catch (const char* e) {  
      cerr << e << endl;  
   }  
   return 0;  
}

执行上面代码,得到以下结果 -

attempted to divide by zero!

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册