[Cython] [cython-users] C++: how to handle failures of 'new'?

Stefan Behnel stefan_ml at behnel.de
Wed Jul 4 08:06:07 CEST 2012


Sturla Molden, 04.07.2012 02:58:
> Den 03.07.2012 20:43, skrev Dag Sverre Seljebotn:
>> Except for the fact that any code touching "new" could be raising
>> exceptions? That propagates.
>>
>> There is a lot of C++ code out there using exceptions. I'd guess that
>> both mathematical code and Google-written code is unlike most C++ code
>> out there :-) Many C++ programmers go on and on about RAII and auto_ptrs
>> and so on, and that doesn't have much point unless you throw an exception
>> now and then (OK, there's the occasional return statement where it
>> matters well).
> 
> Usually there is just one C++ exception to care about: std::bad_alloc. It
> is important to know that it can be raised almost anywhere in C++ code that
> are using the STL.
> 
> The majority of C++ programs never attempt to catch std::bad_alloc. Instead
> a program will set a global handler routine using std::set_new_handler.

Interesting. Doesn't make much sense to do that in Cython, though (and
users wouldn't like it if they intend to use it themselves).


> Usually a callback for memory failure will just display an error message
> and call std::exit with status std::EXIT_FAILURE. ||
> 
> When interfacing from Python I think a std::bad_alloc should be translated
> to a MemoryError exception if possible.  Though others might argue that one
> should never try to recover from a memory failure. Arguably, recovering
> std::bad_alloc might not be possible if the heap is exhausted.

Usually, the intention is more to exit gracefully, i.e. to pass through all
finally clauses, than to actually handle the error and continue. And I
would expect that going back along that path would eventually free up some
memory, so that this should actually work in most cases.

Also, the allocation may have failed on a larger block of memory, which is
then unused when the exception gets raised and can be used by cleanup code.
I really don't think the world is all that dark here.

Stefan


More information about the cython-devel mailing list