C++快速入門---assert函式和捕獲異常(22)
阿新 • • 發佈:2018-11-18
C++快速入門---assert函式和捕獲異常(22)
assert()函式,專為除錯而準備的工具函式。
assert()函式需要有一個引數,它將測試這個輸入引數的真 or 假狀態。
#include <iostream>
#include <cassert>
int main()
{
int i = 20;
assert (i == 65);
return 0;
}
assert()函式可以幫助我們除錯程式。可以利用它在某個程式裡的關鍵假設不成立時立刻停止該程式的執行並報錯,從而避免發生更嚴重的問題。
另外,除了結合assert()函式,在程式的開發、測試階段,我們還可以使用大量的cout語句來報告在程式里正在發生的事情。
捕獲異常
為了對付潛在的程式設計錯誤(尤其在執行時的錯誤)。
異常(exception)就是與預期不相符合的反常現象。
基本使用思路:
1、安排一些C++程式碼(try語句)去嘗試某件事--尤其是那些可能會失敗的事(比如開啟一個檔案或申請一些記憶體)
2、如果發生問題,就丟擲一個異常(throw語句)
3、再安排一些程式碼(catch語句)去捕獲這個異常並進行相應的處理
try
{
//Do something
//Throw an exception on error.
}
catch
{
//Do whatever
}
#include <iostream> #include <climits> unsigned long returnFactorial(unsigned short num) throw (const char *); int main() { unsigned short num = 0; std::cout << "請輸入一個整數:"; while (!(std::cin >> num) || (num<1)) { std::cin.clear(); //清除狀態 std::cin.ignore(100, '\n'); //清楚緩衝區 std::cout << "請輸入一個整數:"; } std::cin.ignore(100, '\n'); try { unsigned long factorial = returnFactorial(num); std::cout << num << "的階乘值是:" << factorial; } catch(const char *e) { std::cout << e; } return 0; } unsigned long returnFactorial(unsigned short num) throw (const char *) { unsigned long sum = 1; unsigned long max = ULONG_MAX; for(int i = 1; i <= num; i++) { sum *= i; max /= i; } if (max < 1) { throw "悲催。。。該基數太大,無法在該計算機計算求出階乘值.\n"; } else { return sum; } }