Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the C++ `new` operator ever throw an exception in real life?

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?


See also:

  • How often do you check for an exception in a C++ new instruction?
  • Is it useful to test the return of “new” in C++?
  • Will new return NULL in any case?
like image 932
osgx Avatar asked Mar 23 '10 02:03

osgx


People also ask

Does operator throw new exception?

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.

Can C throw exception?

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 if new operator fails?

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.

Do we have exceptions in C?

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.


2 Answers

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.

like image 143
James McNellis Avatar answered Nov 03 '22 08:11

James McNellis


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.

like image 37
Brian R. Bondy Avatar answered Nov 03 '22 09:11

Brian R. Bondy