解决set_unexpected不起作用的问题

编译环境: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;
	}
}

解决set_unexpected不起作用的问题_第1张图片

没能正常的调用自己的函数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();
}


解决set_unexpected不起作用的问题_第2张图片


警告: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是否捕获了异常。


 

你可能感兴趣的:(exception,异常处理,vs2012)