如何在C++中捕捉除零錯誤?
以下是捕捉除零錯誤的示例。
示例
#include <iostream>
using namespace std;
int display(int x, int y) {
if( y == 0 ) {
throw "Division by zero condition!";
}
return (x/y);
}
int main () {
int a = 50;
int b = 0;
int c = 0;
try {
c = display(a, b);
cout << c << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}輸出
Division by zero condition!
在以上程式中,定義了一個帶有引數 x 和 y 的函式 display()。它返回 x 除以 y 並丟擲一個錯誤。
int display(int x, int y) {
if( y == 0 ) {
throw "Division by zero condition!";
}
return (x/y);
}在 main() 函式中,使用 try catch 塊,catch 塊捕捉錯誤並列印訊息。
try {
c = display(a, b);
cout << c << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP