错误处理

编程中一般出现的错误有两种:语法上的错误与语义上的错误,语法中的错误几乎都能够被编译器识别出来,但是语义上的错误编译器就无法识别,因此在编程的过程中应该时刻警惕语义错误的出现。

在编程初始,我们可以事先编写防错的程序段,一般错误会出现在什么地方呢?

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: }

posted on 2012-05-28 21:05 钟谢伟 阅读(189) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2012年5月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

导航

统计

常用链接

留言簿(1)

随笔档案

IT网站

My Friends

搜索

最新评论

阅读排行榜

评论排行榜