正文

异常处理ABC2008-04-03 11:08:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/aurora/33888.html

分享到:

此文记录我对异常的一点点基本了解。欢迎大家批评指正。

http://www.microsoft.com/msj/0197/exception/exception.aspx

http://blogs.msdn.com/cbrumme/archive/2003/10/01/51524.aspx

零: c++异常用在哪里?

     In C++, exceptions is used to signal errors that cannot be handled locally, such as the failure to acquire a resource in a constructor. For example:

	class Vector {
		int sz;
		int* elem;
		class Range_error { };
	public:
		Vector(int s) : sz(s) { if (sz<0) throw Range_error(); /* ... */ }
		// ...
	};

Do not use exceptions as simply another way to return a value from a function. Most users assume - as the language definition encourages them to - that exception-handling code is error-handling code, and implementations are optimized to reflect that assumption.

A key technique is resource acquisiton is initialization (sometimes abbreviated to RAII), which uses classes with destructors to impose order on resource management. For example:

	void fct(string s)
	{
		File_handle f(s,"r");	// File_handle's constructor opens the file called "s"
		// use f
	} // here File_handle's destructor closes the file	

If the "use f" part of fct() throws an exception, the destructor is still thrown and the file is properly closed. This contrasts to the common unsafe usage:

	void old_fct(const char* s)
	{
		FILE* f = fopen(s,"r");	// open the file named "s"
		// use f
		fclose(f);	// close the file
	}

If the "use f" part of old_fct throws an exception - or simply does a return - the file isn't closed. In C programs, longjmp() is an additional hazard.

一:两个概念

1)软件异常和硬件异常

      异常区分软件异常和硬件异常,我理解的软件异常是由程序员抛出的,也就是使用C++的throw或者SE的RaiseException函数产生的异常。这是最基本的异常,C++标准支持捕获所有throw产生的异常。(RaiseException异常由SE捕获)

     所谓的硬件异常是由CPU产生的,比如整数除零异常或者内存违规访问异常等。C++标准并不支持此类异常的捕获,但可以通过Windows的SE捕获硬件异常。

2)C++异常与SE

      C++异常受语言支持。而Structured Exception机制是由Windows提供的一种依赖于操作系统的异常,所以SE只能用于Windows,因此一直性能差,但他支持硬件异常的捕获,而C++标准却只能捕获软件异常。

二:并不是所有的异常你都能捕捉

      C++或者SE虽然功能强大,但受限于异常的堆栈回滚机制,不在一个调用堆栈上的异常是无法被捕获的,比如:

      try{

              AThreadPartyFunction();    //第三方的函数

      }

      catch(...){

             cout << "Exception Caught!" << endl;

      }

如果那个第三方的AThreadPartyFunction创建了一个新线程,并且在其中产生了一个未处理的异常,那么这个异常我们并不能捕获到,因为我们的函数与那个产生异常的函数并不在一个调用堆栈里。

三:使C++异常捕获SE

to be continued... ...

阅读(2417) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册