异常 异常迷失方向及注意事项

1>未捕获异常

未捕获异常不会直接导致程序终止 会先调用terminate()->terminate()调用abort()

可以指定terminate()调用的函数而修改用set_terminate()函数
//set_terminate() 和 terminate()都在头文件#include <exception>中

set_terminate():

typedef void (*terminate_handler) ();//定义一个函数指针
terminate_handler set_terminate(terminate_handler f) throw;//一个无参数 无返回 函数
void terminate();


解决方案:

所以可以写个自定义函数
void myquit()
{
  ……
}

在程序开头声明//**//set_terminate(myquit);//**//

 

 

2>意外异常

会先调用unexpected()->unexpected()调用terminate()->terminate()调用abort()

typedef void (*unexpected_handler) ();//定义一个函数指针
unexpected_handler set_unexpected(unexpected_handler f) throw;//一个无参数 无返回 函数
void unexpected();

解决方案:
#include <exception>
using namespace std;

自己定义一个替代函数
void myUnexpected()
{
  throw std::bad_exception();  //bad_exception是exception派生
}

再程序中定义
set_unexpected(myUnexpected);

然后把bad_exception类型规范到函数中
double Argh (double,double)  throw(out_of_bounds,bad_exception);

try
{
 x=Argh(a,b);
}

catch (out_of_bounds & ex)
{……}

catch (bad_exception & ex)
{……}

 

 

 

 

 

 

//*******************************
特别注意

在有 new 分配内存的程序中

因为异常而使函数终止 没能执行对应的 delete

通常需要程序员在对应的catch块中补上对应delete

posted @ 2007-03-11 01:25  Edward Xie  阅读(182)  评论(0)    收藏  举报