在C++编程中,使用try/catch语句执行异常处理。 C++ 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; }
输出:
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-try-catch.html
来源:LearnFk无涯教程网
Floating point exception (core dumped)
#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; }
输出:
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-try-catch.html
来源:LearnFk无涯教程网
Attempted to divide by zero!
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)