C++筆記 | 第7課 異常處理

C++ 筆記 | 第7課 異常處理

C++ 中的異常控制結構的功能是,當函數出現異常,函數的執行被終止,使控制權從函數返回,返回點是調用函數所指定的一個地點,而不是調用發生的地點。

// 拋出異常:
throw 表達式;
// 捕獲異常:
try {函數調用}
catch (聲明) 語句

被調用函數中使用 throw,當滿足條件由 throw 拋出異常,而由 try 捕捉其後面 { } 中函數調用出現的異常,throw 的表達式對應 catch 的聲明。一個 try 塊後可以有多個 catch 分別處理不同的 throw 異常

若程序中有多處要拋出各種不同的異常,應該用不同的 (表達式) 操作數類型來相互區別,操作數的值不能用來區別不同的異常。

#include <stdlib.h>

#include <iostream>
using namespace std;
double Div(double a, double b) {if (b == 0.0) throw 1.0E-308;
  return a / b;
}

int Div(int a, int b) {if (b == 0) throw 0;
  return a / b;
}

int main() {
  try {cout << "5.2/2.0=" << Div(5.2, 2.0) << endl;
    cout << "5/2=" << Div(5, 2) << endl;
    cout << "5.2/0.0=" << Div(5.2, 0.0) << endl;
    cout << "5.2/4.0=" << Div(5.2, 4.0) << endl;
    cout << "5/0=" << Div(5, 0) << endl;
    cout << "5/4=" << Div(5, 4) << endl;
  } catch (double d) {cout << "Exception, float overflow, why->" << d << endl;} catch (int i) {cout << "Exception, integer overflow, why->" << i << endl;}
  cout << "All done!" << endl;
  system("pause");
}
// 結果
5.2/2.0=2.6
5/2=2
5.2/0.0=Exception, float overflow, why->1e-308
All done!
請按任意鍵繼續. . .
// 可以發現到第三行發生錯誤之後, try 塊中第三行後面的都不再執行了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章