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

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

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

例1:自定义一个继承自excepton的异常类myException

C++标准中,定义在<stdexcept>中的任何异常类都派生自exception Class,本例也只是简单地由exception继承,在try段抛出一个异常并捕捉。代码如下:


/*++ test.cpp 
version:1.0 
decript:define a exception class named myException 
    derived from base class exception 
    which is declared in <exception> 
created:2011-08-14 
author: btwsmile 
--*/ 
#include<exception> 
#include<iostream> 
using namespace std; 
 
//customized exception class 'myException' 
class myException:public exception 
{ 
public: 
  myException():exception("ERROR! Don't divide a number by integer zero.n") 
  { 
  } 
}; 
//entry of the application 
int main() 
{ 
  int x=100,y=0; 
  try 
  { 
    if(y==0) throw myException(); 
    else cout<<x/y; 
  } 
  catch(myException& me) 
  { 
    cout<<me.what(); 
  } 
  system("pause"); 
  return 0; 
} 

结果如下:


ERROR! Don't divide a number by integer zero.

请按任意键继续. . .                                                 

显然,异常被捕捉到了。此处需要说明的是,VC对异常处理类exception进行了扩展,本例之所以能够使用exception("ERROR!....")的初始化方法正出于这样的原因,C++标准是不允许这样做的。

与此同时,VC又没有遵循标准,有力地支持terminate和unexpected,它只保留了语法,却在编译运行时不提供支持。为了结合terminate和unexpected更加深入了解C++的异常处理,下面的例子采用Dev cpp IDE实现。

例2:依照C++标准实现自定义异常类myException并将throw语句封装到函数check()中涉及到的更改正如标题所述,(1)重写基类的what()函数,返回错误信息;(2)将throw myException()封装到check()函数中;(3)允许check()函数抛出myException类型的异常。代码如下:


/*++ test.cpp 
version:1.1 
decript:define a exception class named myException 
    according to C++ standard, 
    derived from base class exception 
    which is declared in <exception> 
    !also,encapusulate throw into a function 
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()//#1  
  { 
    return "ERROR! Don't divide a number by integer zero.n"; 
  }   
}; 
void check(int y) throw(myException)//#2 
{ 
   if(y==0) throw myException(); 
} 
//entry of the application 
int main() 
{ 
  int x=100,y=0; 
  try 
  { 
    check(y); 
    cout<<x/y; 
  } 
  catch(myException& me) 
  { 
    cout<<me.what(); 
  } 
  system("pause"); 
  return 0; 
}