C ++中的异常处理 [英] Exception handling in c++

查看:119
本文介绍了C ++中的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在使我的库免受异常影响.我的意思是当我遇到任何异常时-我希望将错误代码返回给库用户模块,而不是使库崩溃或收到系统错误消息.
这是我班的样子:

Hi all,

I am in the process of making my library safe from exceptions.By this I mean when I get any exception - instead of having the library crashed or getting the system error messages,I want to return a error code back to the library user module.
This is how my class looks:

#define BUFFER_SIZE 4096
class CSubClass1{
	private:BYTE *buffer;
	public:
	CSubClass1() {
		buffer = new BYTE[BUFFER_SIZE]; 
		if (buffer == NULL)
		throw 2;
	}
	
};
class CSubClass2{
	private:BYTE *buffer;
	public:
	CSubClass2() {
		buffer = new BYTE[BUFFER_SIZE]; 
		if (buffer == NULL)
		throw 3;
	}
	
};

class CMainClass{
	private:
	BYTE *buffer;
	CSubClass1 *obj1;
	CSubClass2 *obj2;
	public:
	CMainClass() {
		buffer = new BYTE[BUFFER_SIZE]; 
		if (buffer == NULL)
		throw 1;
	}
};

extern "C"  __declspec(dllexport) int function1() {
	StructUtilsSinglyLListNode	*newNode=NULL;
	try{
		newNode->pstData = new CMainClass();
	}
	catch(int retVal){
	UNREFERENCED_PARAMETER(retVal);//for my reference
	return 1;
	}
}
extern "C"  __declspec(dllexport) int function2() {
	StructUtilsSinglyLListNode	*newNode=NULL;
	//code will be present here to fetch node from global list
	//typecast it to CMainClass
	CMainClass *ptr =(CMainClass *) newNode->pstData;
	try{
		ptr->obj1 = new CSubClass1();
		ptr->obj2 = new CSubClass2();
	}
	catch(int retVal){
	UNREFERENCED_PARAMETER(retVal);//for my reference
	return 1;
	}
}



在上面的代码中,我的疑问是:

在function2中,当实例化CSubClass1或CSubClass2时,如果堆上的内存不可用,则会引发异常并将其捕获到异常处理程序中吗?

在此先感谢



In the above code my doubt is:

In function2 when CSubClass1 or CSubClass2 are instantiated,if the memory on the heap is not available will the exception be thrown and caught on the exception handler?

Thanks in advance

推荐答案

一个好主意!不要通过处理异常或将其转化为错误来保护异常!它违背了例外的目的,意味着拒绝使用其权力. 放开他们.

应该在每个线程堆栈的最顶端处理异常,更常见的是在应用程序中而不是在库中.当在更深的上下文中捕获异常时,不应阻止其传播到堆栈.根据经验,应该将其重新抛出.

您只能在某些特殊情况下在本地处理异常(堆栈更深):

1)异常应该在库中以库已知的方式处理,但使用库的代码则不知道.消化原始异常后,该异常可以被成功地完全处理或作为另一个异常重新抛出.例如,在UI库中,可以通过要求用户重新输入数据直到纠正数据来完全覆盖用户输入中的异常.我并不是说这是最佳做法,但是可以接受.在其他情况下,原始异常可以重新抛出为另一个语义"异常.例如,可以重新处理未能以错误格式处理字符串的错误,但会提示建议使用有效格式的列表.

2)抛出异常是指可以处理一些错误"代码,并且如果无法对其进行修补,则可以将其重新抛出以补偿所用API中的缺陷.不过,最好不要破坏无人值守的异常传播.您可以将其写入系统日志或类似的文件中.

3)DLL中会引发异常,但是使用DLL的代码可以用具有不同或没有异常系统的不同语言编写.只有这样,您的方法才可以应用.

-SA
Bad idea! Don''t safeguard exceptions by handling them or turning into errors! It defeats the purpose of exceptions and means denial to use their power. Let them go.

Exceptions should be handled about the very top of the stack of each thread, more typically in application rather then in library. When an exception is caught in a deeper context, its propagation up to stack should not be prevented; as a rule of thumb, it should be re-thrown.

You can handle exceptions locally (deeper on stack) only in some special cases:

1) Exception should be processed in the library in a way known to the library but not to the code using the library. The exception could be successfully fully processed or re-thrown as a different exception, result of digesting of original exception. For example, in UI library, exception in user input could be totally covered by asking the user to re-enter the data until the data it corrected. I don''t say this is the best practice, but it can be accepted. In other cases, raw exception could be re-thrown as a different, "semantic" exception. For example, failure to process a string in a wrong format could be re-worked in the exception suggesting the list of valid formats.

2) Exception thrown is some "bad" code could be handled and not re-thrown to compensate the defects in the API used, in case there is no way to patch it. Still, it''s the best not to break the exception propagation unattended. You can write it in the system log or something like that.

3) Exception is thrown in a DLL, but the code using the DLL can be written in different language with different or no exception system. Only then your approach could be applied.

—SA


操作员new在失败时不返回NULL,它引发std::bad_alloc异常.这使您的测试和throw语句变得无用和多余.因为您没有捕获bad_alloc,它会传播到函数的调用者.
Operator new doesn''t return NULL on failure, it throws the std::bad_alloc exception. That makes your tests and throw statements useless and redundant. Because you''re not catching bad_alloc, it''s propagated to the caller of your functions.


如其他解决方案中所述,这是一个非常糟糕的主意,表明您没有尚未了解例外的目的和工作方式,因此您正试图解决这些问题.

我建议您通过阅读书籍或教程来了解异常.在现实生活中,尤其是在C ++中,如果正确完成了代码,除了在命令无法完成时向用户写一些东西之外,几乎不需要对异常做任何事情.

正如其他人提到的那样,例外的目的与您要尝试的完全相反.目的是避免使用很少检查的错误代码,并使常规代码变得复杂,因为常规逻辑与错误逻辑混合在一起.

您可能需要检查以下几件事:

http://en.wikipedia.org/wiki/Exception_handling [ http://www.parashift.com/c++-faq-lite/exceptions.html [ ^ ]

http://msdn.microsoft.com/en-us/library/4t3saedz.aspx [ ^ ]

而且,如果您想读书,那么可以像杰出的C ++ [ ^ ]会成为推荐的读物.
As mentionned in other solutions, this is a very bad idea that show you didn''t yet understand the purpose and working of exceptions... and you are trying to work around them because of that.

I would suggest you to learn about exception by reading books or tutorial. In real life and in particular in C++, you rarely have to do anything about exception if the code is properly done except writing something to the user when a command cannot be completed.

As others have mentionned, the purpose of exception is exactly the opposite of what you are trying to do. The purpose is to avoid the using of error codes that are seldom checked and make the regular code complex to understand because regular logic is mixed with error logic.

Here is a few things you might want to check:

http://en.wikipedia.org/wiki/Exception_handling[^]

http://www.parashift.com/c++-faq-lite/exceptions.html[^]

http://msdn.microsoft.com/en-us/library/4t3saedz.aspx[^]

And if you like to read books, then book like Exceptional C++[^] would be a recommanded reading.


这篇关于C ++中的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆