什么时候适合使用C ++异常? [英] When is it appropriate to use C++ exceptions?

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

问题描述

我试图设计一个需要动态分配一些内存的类。



我已经计划在构建过程中分配它需要的内存,但是如何我处理失败的内存分配?我应该抛出异常吗?我读到某个地方,例外应该仅用于特殊的情况,而且内存不足似乎不是特例。



我应该分配记住在一个单独的初始化程序中,检查失败,然后优雅地破坏类实例?



还是应该使用异常?如果这些内存分配失败,该类别将无法做到这一点。






编辑:这是一个例外情况。



将会看到如何解决..谢谢..:)

解决方案>

假设您正在使用新的内存分配,并且不会覆盖新的运算符,它将自动抛出 std :: bad_alloc 异常,如果它无法正确分配内存。


我读到某个地方,例外
只能使用对于特殊
的案例,内存不足
似乎不是一个例外情况
给我..


内存不足似乎是一个非常特殊的情况:)



很难处理这种情况。您可能想要向应用程序的用户返回有意义的错误,但是如果由于内存不足而导致的问题,您可能甚至无法负担内存分配错误消息。这真的是一个catch-22的情况。



有一种防御性编程技术(有时称为内存降落伞或雨天基金),您可以在其中分配一大块内存当您的应用程序启动当您处理 bad_alloc 异常时,您将释放此内存,并使用可用内存来正常关闭应用程序,包括向用户显示有意义的错误。这比崩溃要好得多:)


I'm trying to design a class that needs to dynamically allocate some memory..

I had planned to allocate the memory it needs during construction, but how do I handle failed memory allocations? Should I throw an exception? I read somewhere that exceptions should only be used for "exceptional" cases, and running out of memory doesn't seem like an exceptional case to me..

Should I allocate memory in a separate initialization routine instead and check for failures and then destroy the class instance gracefully?

Or should I use exceptions instead? The class won't have anything useful to do if these memory allocations should fail..


EDIT: The consensus seems to be that running out of memory IS an exceptional case.

Will see how to go about this.. Thanks.. :)

解决方案

Assuming you are using new to allocate memory, and are not overriding the new operator, it will automatically throw the std::bad_alloc exception if it fails to allocate memory properly.

I read somewhere that exceptions should only be used for "exceptional" cases, and running out of memory doesn't seem like an exceptional case to me..

Running out of memory seems like a pretty exceptional case to me :)

It is very difficult to handle this sort of situation. You may want to return a meaningful error to the user of your application, but if it's a problem caused by lack of memory, you may not even be able to afford the memory to allocate the error message. It's a bit of a catch-22 situation really.

There is a defensive programming technique (sometimes called a memory parachute or rainy day fund) where you allocate a chunk of memory when your application starts. When you then handle the bad_alloc exception, you free this memory up, and use the available memory to close down the application gracefully, including displaying a meaningful error to the user. This is much better than crashing :)

这篇关于什么时候适合使用C ++异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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