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

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

结果与例1完全相同。需说明的是,紧跟check()后的throw列表表明允许该函数抛出的异常类型。这里不得不产生疑问,如果抛出了一个不被允许的异常类型将怎样?

例3:抛出unexpected异常

check函数体之后的throw列表,规定了允许抛出的异常类型,一旦违背,就将触发unexpected。可以把unexpected看作系统自动调用的CALLBACK函数,不同的是,也可以手工触发它的执行。本例的情况属于前者。代码如下:


 
/*++ test.cpp 
version:1.3 
decript:define an unexpected excption handler, 
    set it by using set_unexpected, 
    modify the throw list of function check 
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) throw()//#1 only int-type exception is permitted 
{ 
   if(y==0) throw myException(); 
} 
void myUnexpected() 
{ 
   cout<<"Unexpected exception caught!n"; 
   system("pause"); 
   exit(-1); 
} 
//entry of the application 
int main() 
{ 
  unexpected_handler oldHandler=set_unexpected(myUnexpected); 
  int x=100,y=0; 
  try 
  { 
    check(y); 
    cout<<x/y; 
  } 
  catch(myException& me) 
  { 
    cout<<me.what(); 
  } 
  system("pause"); 
  return 0; 
} 

结果如下:


Unexpected exception caught!

请按任意键继续. . .                   

check函数的throw列表为空,即不允许抛出任何类型的异常,然而实际上当异常发生时,系统不能等闲视之,它将调用unexpected处理方法。所以,限定一个函数throw列表为空是值得程序员警醒的事,需要特别留意。如果将#1处的代码修改为throw(int)等也能得到相同的结果。所谓unexpected异常,说白了就是函数体允许抛出异常类型范围之外的异常。如果check函数后面根本没有throw,则表示函数任何类型的异常都被允许。

例4:抛出函数体允许的异常,但没被捕捉到的情况

思考这样一个问题,如果函数check的throw列表中有异常类型myException,而且在y==0时,它的确抛出myException类型的异常,但是没有被catch到,这时会发生什么?

在正式回答这个问题之前,先讨论“没被catch到”的意思。比如,修改例3的代码如下:(##为修改之处)


/*++ test.cpp 
version:1.4.1 
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); 
} 
//entry of the application 
int main() 
{ 
  unexpected_handler oldHandler=set_unexpected(myUnexpected); 
  int x=100,y=0; 
  try 
  { 
    check(y); 
    cout<<x/y; 
  } 
  catch(int &e) //##1 no catch sentence matches the throw type 
  { 
    cout<<e<<endl; 
  } 
  /*        ##2 if add this part, any type which's not handler before will 
            be caught 
  catch(...) 
  { 
          cout<<"Unkown exception caught!n"; 
     } 
  */ 
  system("pause"); 
  return 0; 
}