Search code examples
c++classerror-handlinginstancethrow

Throw error on max instantiations of class


I want my program to throw an error when a defined maximum number of objects of a certain class (MAX) is reached. I must limit the number of instantiations because I'm working with a framework that provides a limited amount of resources.

Currently I have the following (simplified):

class Resource {
    private:
    static int count;

    public:
    Resource();
};

int Resource::count = 0;

Resource::Resource() {
    if (++count > MAX) {
        throw std::domain_error("Cannot create more resources.");
    }
}

Is the use of std::domain_error recommended or should I use another type? Or should I not throw an error at all and follow a different approach?


Solution

  • I will answer the general question, without considering any of the details of the application.

    Is the use of std::domain_error recommended or should I use another type? Or should I not throw an error at all and follow a different approach?

    Regarding which exception to throw: std::domain_error specifically has to do with the argument of a function being outside the allowed range, so that is not a good fit. As @NathanOliver suggests, std::runtime_error would be a good option. Or a custom exception derived from that.

    Regarding throwing an exception or using a different approach: An important question is when the error is expected to happen and who can handle it.

    Exceptions are typically used for errors that can happen during normal operation, and preferably be handled at run-time.

    If the amount of resources allocated is determined during development, and excessive allocation of resources indicates a bug, then an assertion is an option:

    Resource::Resource() {
        assert(++count <= MAX);
    }
    

    That will make a debug-build of the program crash (fail-fast) if the limit is exceeded, which is often quite useful during development, testing, and debugging but should obviously not be used if the limit can be exceeded in the finished product. (As assertions are typically removed in release builds it would go unnoticed and cause whatever problems or undefined behaviour exceeding the limit would cause).