举例说明自定义C++异常处理的实例

2020-01-06 17:21:04王冬梅

编译运行,程序将会出错,因为check函数抛出的myException异常没有被处理。在缺省情况下,一旦出现抛出异常没被处理的问题,系统将自动调用abort()函数,终止程序允许,在控制台将会看到这样的提示:


This application has requested the Runtime to terminate it in an unusual way.Please contact the 
application's support team for more information.

不过可以增加##2部分的代码,catch(...)表示捕捉任何类型的异常。

注意:check函数不被允许的异常类型并不会进入到catch语句的判断中来,因此catch(...)对unexpected exception没有作用。
仍然考虑没有##2部分的情况。正如前面所述,系统将自动调用abort()函数终止程序。实际上,它触发的是terminate,类似于unexpected,仍然可以自定义terminate的处理方法。甚至terminate语法上跟unexpected都十分近似。修改代码为:


/*++ test.cpp 
version:1.4.2 
decript: 
    how to understand "exception not caucht"? 
created:2011-08-14 
author: btwsmile 
--*/ 
#include<exception> 
#include<iostream> 
using namespace std; 
 
//customized exception class 'myException' 
class myException:public exception 
{ 
public: 
  const char* what()const throw() 
  { 
    return "ERROR! Don't divide a number by integer zero.n"; 
  }   
}; 
void check(int y) //any type of exception is permitted 
{ 
   if(y==0) throw myException(); 
} 
void myUnexpected() 
{ 
   cout<<"Unexpected exception caught!n"; 
   system("pause"); 
   exit(-1); 
} 
void myTerminate() //##1 set it be the terminate handler 
{ 
   cout<<"Unhandler exception!n"; 
   system("pause"); 
   exit(-1); 
} 
//entry of the application 
int main() 
{ 
  unexpected_handler oldHandler=set_unexpected(myUnexpected); 
  terminate_handler preHandler=set_terminate(myTerminate); 
  int x=100,y=0; 
  try 
  { 
    check(y); 
    cout<<x/y; 
  } 
  catch(int &e) //no catch sentence matches the throw type 
  { 
    cout<<e<<endl; 
  } 
  system("pause"); 
  return 0; 
} 

结果如下:


Unhandler exception!

请按任意键继续. . .   

结论:C++为异常处理提供了友好的支持。

用户可以自定义异常类型,异常类型并不受到限制,可以是内建数据类型如int,double等,也可以是自定义的类,也可以从C++某个异常类继承下来。例1采用了派生自exception的方法。

除此之外,在定义函数时,可以显式指定函数体抛出的异常类型。隐式情况下,缺省允许函数抛出任何类型的异常。有可以增加throw语句,对异常类型加以限制。特别的是,throw()表示不允许函数抛出任何类型的异常。如果违反了throw列表规定的异常类型,系统将调用unexpected hanlder进行处理,可以自定义unexpected异常处理方法。例2和例3对它们进行了说明。