Chinaunix首页 | 论坛 | 博客
  • 博客访问: 293554
  • 博文数量: 81
  • 博客积分: 1400
  • 博客等级: 上尉
  • 技术积分: 952
  • 用 户 组: 普通用户
  • 注册时间: 2009-07-31 22:05
文章分类

全部博文(81)

文章存档

2011年(1)

2010年(1)

2009年(79)

我的朋友

分类: C/C++

2009-08-07 16:34:08

 ●用assert测试编码和设计错误。如果其返回false,则程序终止,应纠正代码。这种方法在调试时很有用处。
 ●忽略异常,这不适合公开发布的软件产品和任务关键的专用软件。但自用软件通常可以忽略许多错误。退出程序,使程序无法运行完毕或产生错误结果。实际上,对于许多错误类型,这是个好办法,特别是对于能让程序运行完毕的非致命错误,因为让程序运行完毕很可能使程序员误以为程序工作很顺利。这种方法也不适合任何任务关键的应用程序。资源问题也很重要,如果程序取得资源,则应先正常返回资源之后再终止。

    常见编程错误    退出程序会使其他程序无法使用其资源,从而造成资源泄漏。

 ●设置一些错误指示符。这里的问题是程序不一定在发生错误的所有地方都检查这些错误指示符。
 ●测试错误条件、发出错误消息和调用exit,向程序环境传递相应的错误代码。
 ●setjump和longjump。这个功能通过实现,可以指定从深层嵌套函数立即转入错误处理器。如果没有setjump/longjump,则程序要执行几个返回才能从深层嵌套函数退出。这种方法可以转入某个错误处理器。但其在C++中有危险性,因为其解退堆栈而不调用自动对象的析构函数,从而可能造成严重问题。
 ●某些特定错误有专门的处理功能。例如,new无法分配内存时,可以用new_handler函数处理错误。通过提供函数名作为set_new_handler的参数可以改变这个函数。

1.在try块中放上出错时产生异常的代码。try块后面是一个或几个catch块。每个catch块指定捕获和处理一种异常,而且每个catch块包含一个异常处理器。如果异常与catch块中的参数类型相符,则执行该catch块的代码。如果找不到相应异常处理器,则调用,terminate函数(默认调用函数abort)。

下面考虑一个简单异常处理例子。图13.1的程序用try、throw和catch检测除数为0的异常情况,表示并处理除数为0的异常。
1 // Fig. 13.1:fig13_01.cpp
2 // A simple exception handling example.
3 // Checking for a divide-by zero exception.
4 #include
5
6 // Class DivideByZeroException to be used in exception
7 // handling for throwing an exception on a division by zero.
8 class DivideByZeroException {
9 public:
10   DivideByZeroException()
11      : message( "attempted to divide by zero" ) { }
12   const char *what() const { return message; }
13 private:
14   const char *message;
15 };
16
17 // Definition of function quotient, Demonstrates throwing
18 // an exception when a divide-by-zero exception is encountered.
19 double quotient( int numerator, int denominator )
2O {
21   if ( denominator == 0 )
22     throw DivideByZeroException();
23
24   return staticcast< double > ( numerator ) / denominator;
25 }
26
27 // Driver program
28 int main()
29 {
30   int nunber1, number2;
31   double result;
32
33   cout << "Enter two integers (end-of-file to end): ";
34
35   while ( cin >> number1 >> number2 ) {
36
37     // the try block wraps the code that may throw an
38     // exception and the code that should not execute
39     // if an exception occurs
40     try {
41        result = quotient( numberl, number2 );
42        cout << "The quotient is: "<< result << endl;
43     }
44     catch ( DivideByZeroException ex ) { // exception handler
45        cout << "Exception occurred: "<< ex.what() << '\n';
46     }
47
48     cout << "\nEnter two integers (end-of-file to end): ";
49        }
50
51   cout << endl;
52   return 0;     // terminate normally
53 }

输出结果:
Enter tow integers (end-of-file to end); l00 7
The quotient is: 14.2857

Enter tow integers (end-of-file to end); 100 0
Exception occurred: attempted to divide by zero

Enter tow integers (end-of-file to end); 33 9
The quotient is: 3.66667

Enter tow integers {end-of-file to end):


阅读(470) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~