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!