C++ try/catch语句
在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!
本站文章除注明转载外,均为本站原创或编译
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动共创优秀实例教程
转载请注明:文章转载自:代码驿站 [http:/www.codeinn.net]
本文标题:C++ try/catch语句
本文地址:http://www.codeinn.net/cplus/1846.html
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动共创优秀实例教程
转载请注明:文章转载自:代码驿站 [http:/www.codeinn.net]
本文标题:C++ try/catch语句
本文地址:http://www.codeinn.net/cplus/1846.html