如何在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;
}

更新時間: 26-6 月-2020

595 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.