編程中一般出現的錯誤有兩種:語法上的錯誤與語義上的錯誤,語法中的錯誤幾乎都能夠被編譯器識別出來,但是語義上的錯誤編譯器就無法識別,因此在編程的過程中應該時刻警惕語義錯誤的出現。
在編程初始,我們可以事先編寫防錯的程序段,一般錯誤會出現在什么地方呢?
1)函數調用時傳遞的參數的有效性
2)函數的返回值可能隱含了錯誤發生的可能
3)從用戶或文件中讀取的輸入導致的錯誤
為了很好的避免這些錯誤,我們通常遵循如下的措施:
1)在函數的頂部,確保傳遞進來的參數有效
2)函數調用后,檢測返回值
3)使輸入的值有效,符合規范
那么選取怎樣的方式對錯誤進行處理呢,一般如下:
1)快速跳過代碼
1: void PrintString(char *strString)
2: {
3: // Only print if strString is non-null
4: if (strString)
5: std::cout << strString;
6: }
2)想調用程序中,返回錯誤碼
1: int g_anArray[10]; // a global array of 10 characters
2:
3: int GetArrayValue(int nIndex)
4: {
5: // use if statement to detect violated assumption
6: if (nIndex < 0 || nIndex > 9)
7: return -1; // return error code to caller
8:
9: return g_anArray[nIndex];
10: }
3)如果你想在發現錯誤時直接終止程序,可以使用exit函數
1: int g_anArray[10]; // a global array of 10 characters
2:
3: int GetArrayValue(int nIndex)
4: {
5: // use if statement to detect violated assumption
6: if (nIndex < 0 || nIndex > 9)
7: exit(2); // terminate program and return error number 2 to OS
8:
9: return g_anArray[nIndex];
10: }
4)如果用戶輸入不合理的值,就繼續要求輸入
1: char strHello[] = "Hello, world!";
2:
3: int nIndex;
4: do
5: {
6: std::cout << "Enter an index: ";
7: std::cin >> nIndex;
8: } while (nIndex < 0 || nIndex >= strlen(strHello));
9:
10: std::cout << "Letter #" << nIndex << " is " << strHello[nIndex] << std::endl;
5)可以使用cerr輸出錯誤,在gui編程的時候,可以直接在遇到錯誤的時候跳出對話框,輸出錯誤碼,然后終止
1: void PrintString(char *strString)
2: {
3: // Only print if strString is non-null
4: if (strString)
5: std::cout << strString;
6: else
7: std::cerr << "PrintString received a null parameter";
8: }
另,可以使用assert
1: int g_anArray[10]; // a global array of 10 characters
2:
3: #include <cassert> // for assert()
4: int GetArrayValue(int nIndex)
5: {
6: // we're asserting that nIndex is between 0 and 9
7: assert(nIndex >= 0 && nIndex <= 9); // this is line 7 in Test.cpp
8:
9: return g_anArray[nIndex];
10: }