user14754470
user14754470

Reputation:

catch only memory issues C++

What is the exception type I can catch to detect any memory issues?

I want to detect when new fails, or c'tor of class fails.

catch (Exception &e) is too broad and doesn't only catch memory issues.

Note: I remember there was such a type but forgot it, it starts with std::

Upvotes: 0

Views: 62

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595339

If new fails because it itself is not able to allocate memory for the new object prior to calling the object's constructor, it will throw a std::bad_alloc exception.

If memory for the object is allocated successfully, and then the constructor throws its own exception for any reason, new will cancel the construction, free the memory it was able to allocate, and re-throw whatever exception the constructor threw.

Unless you use the nothrow version of new, in which case it will silently discard any exception thrown and return a nullptr instead.

Upvotes: 1

Potatoswatter
Potatoswatter

Reputation: 137770

Running out of memory throws std::bad_alloc, if the operating system chooses to report the problem to the application.

Constructors can do more than allocate memory, and they can throw whatever they want.

Here is an overview of all the standard exception classes.

Upvotes: 3

Related Questions