Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Policy with catching std::bad_alloc

So I use Qt a lot with my development and love it. The usual design pattern with Qt objects is to allocate them using new.

Pretty much all of the examples (especially code generated by the Qt designer) do absolutely no checking for the std::bad_alloc exception. Since the objects allocated (usually widgets and such) are small this is hardly ever a problem. After all, if you fail to allocate something like 20 bytes, odds are there's not much you can do to remedy the problem.

Currently, I've adopted a policy of wrapping "large" (anything above a page or two in size) allocations in a try/catch. If that fails, I display a message to the user, pretty much anything smaller, I'll just let the app crash with a std::bad_alloc exception.

So, I wonder what the schools of thought on this are on this?

Is it good policy to check each and every new operation? Or only ones I expect to have the potential to fail?

Also, it is clearly a whole different story when dealing with an embedded environment where resources can be much more constrained. I am asking in the context of a desktop application, but would be interested in answers involving other scenarios as well.

like image 745
Evan Teran Avatar asked Aug 20 '09 18:08

Evan Teran


1 Answers

Handle the exception when you can. If an allocation fails, and your application can't continue without that bit of memory, why bother checking for the error?

Handle the error when it can be handled, when there is a meaningful way to recover. If there's nothing you can do about the error, just let it propagate.

like image 83
jalf Avatar answered Sep 17 '22 19:09

jalf