C++教程-C++try/catch语句
在 C++ 编程中,使用 try/catch 语句进行异常处理。C++ 的 try 块用于放置可能引发异常的代码。catch 块用于处理异常。
没有 try/catch 的 C++ 示例:
#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)
带有 try/catch 的 C++ 示例:
#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!