解决set_unexpected不起作用的问题

13 篇文章 0 订阅

编译环境:vs2012


按照Think in c++中写了一段代码


#include "stdafx.h"
#include <iostream>
#include <string>


using namespace std;
class up {};
class fit {};
void g();

void f(int i) throw (up,fit)
{
	switch (i){
	case 1:  throw up();
	case 2:  throw fit();
	}
	g();
}

void g() { throw 47; }//抛出异常后怎么没有调用my_unexpected(),出现debug error ,用abort()结束了进程

	void my_unexpected ()
{
	cout<<"unexpected exception thrown ";
	exit(1);
}

void main()
{
	set_unexpected(my_unexpected);
;
	for(int i=1;i<=3;i++)
		try{
			f(i);
	} catch (up) {
		cout<<"up canght"<<endl;
	} catch (fit) {
		cout<<"fit canght"<<endl;
	}
}


没能正常的调用自己的函数my_unexpected ()处理意外的异常

查阅MSND后发现,要调用自己的意外异常处理函数,必须显式的调用

  unexpected(); // library function to force calling the current unexpected handler


调用此函数后程序正常,如下

#include "stdafx.h"
#include <iostream>
#include <string>


using namespace std;
class up {};
class fit {};
void g();

void f(int i) throw (up,fit)
{
	switch (i){
	case 1:  throw up();
	case 2:  throw fit();
	}
	g();
}

void g() { throw 47; }//抛出异常后怎么没有调用my_unexpected(),出现debug error ,用abort()结束了进程

void my_unexpected ()
{
	cout<<"unexpected exception thrown ";
	exit(1);
}

void main()
{
	set_unexpected(my_unexpected);//使用vs编译器时不推荐使用
	
	for(int i=1;i<=3;i++)
		try{
			f(i);
	} catch (up) {
		cout<<"up canght"<<endl;
	} catch (fit) {
		cout<<"fit canght"<<endl;
	}
	unexpected();
}




警告:MSDN中是这样说的The C++ Standard requires that unexpected is called when a function throws an exception that is not on its throw list. The current implementation does not support this. The following example calls unexpected directly, which then calls theunexpected_handler.


C++标准中要求unexpected 在catch时候没有匹配时被调用,但是vs编译器现在还不支持,上面的例子是强制的调用 my_unexpected () ,不管catch是否捕获了异常。



                
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值