Can the new
operator throw an exception in real life?
And if so, do I have any options for handling such an exception apart from killing my application?
Update:
Do any real-world, new
-heavy applications check for failure and recover when there is no memory?
The nothrow constant value is used as an argument for operator new and operator new[] to indicate that these functions shall not throw an exception on failure but return a null pointer instead.
C doesn't support exception handling. To throw an exception in C, you need to use something platform specific such as Win32's structured exception handling -- but to give any help with that, we'll need to know the platform you care about. ...and don't use Win32 structured exception handling.
What happens when new fails? Explanation: While creating new objects, the new operator may fail because of memory errors or due to permissions. At that moment the new operator returns zero or it may throw an exception. The exception can be handled as usual.
The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.
Yes, new
can and will throw if allocation fails. This can happen if you run out of memory or you try to allocate a block of memory too large.
You can catch the std::bad_alloc
exception and handle it appropriately. Sometimes this makes sense, other times (read: most of the time) it doesn't. If, for example, you were trying to allocate a huge buffer but could work with less space, you could try allocating successively smaller blocks.
The new operator, and new[] operator should throw std::bad_alloc
, but this is not always the case as the behavior can be sometimes overridden.
One can use std::set_new_handler
and suddenly something entirely different can happen than throwing std::bad_alloc
. Although the standard requires that the user either make memory available, abort, or throw std::bad_alloc
. But of course this may not be the case.
Disclaimer: I am not suggesting to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With